Python Standard library-logging

Source: Internet
Author: User


When writing code, it is often necessary to keep track of the process under which logging is used. The simple thing is that the print command prints to the terminal or writes to the file via the Open function. However, with the increase of the code volume, the drawback of the way is not controllable, also highlighted, which is the background of the logging module appears.



For the logging module, simply import it in, you can use it.

In [1]: Import logging


In [2]: logging.warning (' Watch out! ')

WARNING:root:Watch out!


In [3]: logging.info (' I told-so ')


In [4]:


In [4]:


The second statement has no output, which requires an understanding of the concept of a log level. The default log level for the logging module is warning, and logs larger than that level will be output, as detailed below.

Level When it ' s used
DEBUG Detailed information, typically of interest only when diagnosing problems.
INFO Confirmation that things is working as expected.
WARNING An indication this something unexpected happened, or indicative of some problem in the "near" (e.g. ' disk space low ') . The software is still working as expected.
ERROR Due to a more serious problem, the software have not been able to perform some function.
CRITICAL A serious error, indicating the program itself is unable to continue running.


With the Basicconfig method, you can configure the log records.

In [1]: Import logging


In [2]: Logging.basicconfig (filename= '/tmp/example.log ', level=logging. DEBUG)


In [3]: Logging.debug (' This message should go to the log file ')


In [4]: Logging.info (' so should this ')


In [5]: logging.warning (' And this, too ')


$ cat/tmp/example.log

DEBUG:root:This message should go to the log file

INFO:root:So should this

WARNING:root:And this, too


In the script, you can use the logging module as follows.

#!/usr/bin/env python

#-*-Coding:utf-8-*-

# myapp.py


Import logging

Import Mylib


def main ():

Logging.basicconfig (filename= ' Myapp.log ', format= '% (asctime) s-% (name) s-% (levelname) s-% (pathname) s-% (message) s ', Level=logging.info)

Logging.info (' Started ')

Mylib.do_something ()

Logging.info (' finished ')


if __name__ = = ' __main__ ':

Main ()


#!/usr/bin/env python

#-*-Coding:utf-8-*-

# mylib.py


Import logging


Def do_something ():

Logging.info (' Doing something ')


$ python myapp.py

$ cat Myapp.log

2018-01-19 17:00:14,821-root-info-myapp.py-started

2018-01-19 17:00:14,821-root-info-/home/zz/stage/mylib.py-doing Something

2018-01-19 17:00:14,821-root-info-myapp.py-finished



A brief look at the use of the logging module, followed by a few important concepts.

1. Logger logger, exposed to the application directly using the interface, several methods for setting the logger.


Logger.setlevel ()-Specifies the lowest level of logging processed by the logger.

Logger.addhandler (), Logger.removehandler ()-Adds or removes the processor for the logger.


2. The Handler processor, which transmits the log captured by the logger to its defined destination, also has several methods for setting up the processor.


SetLevel ()-Specifies the lowest level of logging processed by the processor.

Setformatter ()-Select a formatter for the processor.


3. Formatter Formatter, specifies the output format of the log.



Starting with the simple usage of the logging module and understanding the concepts above, how to use logging when developing larger applications.


This is mainly about two ways, one is to write the configuration of the logging module directly in the application code, as shown below.

#!/usr/bin/env python

#-*-Coding:utf-8-*-

# simple_logging_module.py


Import logging


# Create Logger

Logger = Logging.getlogger (' simple_example ')

Logger.setlevel (logging. DEBUG)


# Create console handler and set level to debug

ch = logging. Streamhandler ()

Ch.setlevel (logging. DEBUG)


# Create Formatter

Formatter = logging. Formatter ('% (asctime) s-% (name) s-% (levelname) s-% (message) s ')


# Add Formatter to Ch

Ch.setformatter (Formatter)


# Add CH to Logger

Logger.addhandler (CH)


# ' Application ' code

Logger.debug (' Debug message ')

Logger.info (' info message ')

Logger.warn (' Warn message ')

Logger.error (' Error message ')

Logger.critical (' critical message ')


$ python simple_logging_module.py

2018-01-19 21:41:58,180-simple_example-debug-debug Message

2018-01-19 21:41:58,180-simple_example-info-info Message

2018-01-19 21:41:58,180-simple_example-warning-warn Message

2018-01-19 21:41:58,180-simple_example-error-error Message

2018-01-19 21:41:58,180-simple_example-critical-critical Message


Secondly, the configuration information is written to the file, and the file is loaded with the Fileconfig method, as shown below.

#!/usr/bin/env python

#-*-Coding:utf-8-*-

# simple_logging_config.py


Import logging

Import Logging.config


Logging.config.fileConfig (' logging.conf ')


# Create Logger

Logger = Logging.getlogger (' simpleexample ')


# ' Application ' code

Logger.debug (' Debug message ')

Logger.info (' info message ')

Logger.warn (' Warn message ')

Logger.error (' Error message ')

Logger.critical (' critical message ')


# logging.conf

[Loggers]

Keys=root,simpleexample


[Handlers]

Keys=consolehandler


[Formatters]

Keys=simpleformatter


[Logger_root]

Level=debug

Handlers=consolehandler


[Logger_simpleexample]

Level=debug

Handlers=consolehandler

Qualname=simpleexample

Propagate=0


[Handler_consolehandler]

Class=streamhandler

Level=debug

Formatter=simpleformatter

Args= (Sys.stdout,)


[Formatter_simpleformatter]

format=% (asctime) s-% (name) s-% (levelname) s-% (message) s

datefmt=


$ python simple_logging_config.py

2018-01-19 21:53:46,216-simpleexample-debug-debug Message

2018-01-19 21:53:46,216-simpleexample-info-info Message

2018-01-19 21:53:46,216-simpleexample-warning-warn Message

2018-01-19 21:53:46,216-simpleexample-error-error Message

2018-01-19 21:53:46,216-simpleexample-critical-critical Message



Finally, briefly, how to summarize a module, can be described around the following three points.

1. The module solves the problem, and the other method is how to do it.

2. The use of modules, as well as core concepts (or definitions).

3. Comb the core API.


If interested, you can follow the subscription number "database Best practices" (Dbbestpractice).

Python Standard library-logging

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.