For details about how to use logging in python, pythonlogging

Source: Internet
Author: User

For details about how to use logging in python, pythonlogging

Logs are used to record the status of a program during running. Adding a log module during program development can help us understand what events occur during the program running. These events are also important.

Based on the severity of the event, it can be divided into the following levels:

DEBUG: detailed information, which is usually followed only when a problem is diagnosed. Integer level = 10

INFO: The validation program works as expected. Integer level = 20

WARNING: exception occurred, but normal operation is not affected. Integer level = 30

ERROR: for some reason, the program cannot execute certain functions. Integer level = 40

CRITICAL: The program cannot run due to a serious error. Integer level = 50

The default level is WARNING, which means that only those with a level greater than or equal to can be seen. The tracing log can be written to a file or directly output to the console.

Output to console

The following is a small example of how to output logs to the console:

Import logginglogging. warning ('Watch out! ') # Output to the console logging.info (' I told you so') # logging. error ("an error occurrence! ") # Output to the console

Output result

WARNING:root:Watch out!ERROR:root:an error occurrence

Output to file

Create a new python interpreter to make sure it is not the session of the above Code

import logginglogging.basicConfig(filename='example.log',level=logging.DEBUG)logging.debug('This message should go to the log file')logging.info('So should this')logging.warning('And this, too')

At this time, no output is available on the console. The content in the file example. log

DEBUG:root:This message should go to the log fileINFO:root:So should thisWARNING:root:And this, too

If you need to manually adjust the log level, you can input -- log = INFO as a parameter in the command line. The following processing method can be used in the Code:

# Input parameter -- log = DEBUG or -- log = debugnumeric_level = getattr (logging, loglevel. upper (), None) # return 10, otherwise Noneif not isinstance (numeric_level, int): raise ValueError ('invalidlog level: % s' % loglevel) logging. basicConfig (level = numeric_level ,...)

Variable log

Add logs for variables by formatting strings

import logginglogging.warning('%s before you %s', 'Look', 'leap!')

Custom log format

We can also customize the output template as needed.

import logginglogging.basicConfig(format='%(asctime)s: %(levelname)s: %(message)s',level=logging.DEBUG)logging.debug('This message should appear on the console')logging.info('So should this')logging.warning('And this, too')

Output

2017-10-24 14:03:53,671: DEBUG: This message should appear on the console2017-10-24 14:03:53,690: INFO: So should this2017-10-24 14:03:53,694: WARNING: And this, too

Actually passed in is a dictionary, and % (key) is the dictionary key.

The above are some basic usage of the python logging module, which can meet many of our requirements. The following describes some advanced usage of logging. The logging module mainly includes logger, handlers, filter, and formatters.

Logger: provides application interfaces for applications.
Handlers: used to send the logs created by logger to the corresponding destination.
Filter: provides more fine-grained settings for logs to be output.
Formatters: set the final output format

The following is an example of how to use these components.

Import logginglogger = logging. getLogger ('logger _ name') # create a logger object. setLevel (logging. DEBUG) handler = logging. streamHandler () # create a console handler and set its level to debughandler. setLevel (logging. DEBUG) formatter = logging. formatter ('% (asctime) s-% (name) s-% (levelname) s-% (message) s') # create the output format handler. setFormatter (formatter) # Add fromatterlogger for handler. addHandler (handler) # Add handler to loggerlogger. debug ('debug message') # 'application' codelogger.info ('info message') logger. warn ('warn message') logger. error ('error message') logger. critical ('critical message ')

Output result:

16:50:43, 127-logger_name-DEBUG-debug message
2017-10-24 16:50:43, 138-logger_name-INFO-info message
16:50:43, 141-logger_name-WARNING-warn message
16:50:43, 144-logger_name-ERROR-error message
16:50:43, 148-logger_name-CRITICAL-critical message

Small application cases

The following is a custom log processing method, which can be written to a file (scroll to save logs for the last 15 days, log format app. log, app. log.1, app. log.2), and can be output to the console.

Import loggingfrom logging. handlers import TimedRotatingFileHandlerclass MylogHandler (logging. logger): def _ init _ (self, name, level = "DEBUG", stream = True, files = True): self. name = name self. level = level logging. logger. _ init _ (self, self. name, level = self. level) if stream: self. _ streamHandler _ (self. level) if files: self. _ filesHandler _ (self. level) def _ streamHandler _ (self, level = None): handler = TimedRotatingFileHandler (filename = self. name + ". log ", when = 'D', interval = 1, backupCount = 15) handler. suffix = '% Y % m % d. log 'handler. setLevel (level) formatter = logging. formatter ('% (asctime) s % (filename) s [line: % (lineno) d] % (levelname) s % (message) s') handler. setFormatter (formatter) self. addHandler (handler) # Add hander to logger def _ filesHandler _ (self, level = None): handler = logging. streamHandler () formatter = logging. formatter ('% (asctime) s % (filename) s [line: % (lineno) d] % (levelname) s % (message) s') handler. setFormatter (formatter) handler. setLevel (level) self. addHandler (handler) if _ name _ = '_ main _': log = MylogHandler ('test') log.info ('this is a my log handler ')

Summary

The above is a detailed description of the use of logging in python. I hope it will be helpful to you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!

Related Article

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.