Python logging library usage summary, pythonlogging

Source: Internet
Author: User

Python logging library usage summary, pythonlogging

Preface

Recently, due to work requirements, it is very low to write some python scripts and print is always used to print information. So I took the time to study the python logging library, let's print and record the logs elegantly. Let's talk a little more about it. Let's take a look at the detailed introduction.

1. Simply print logs to the screen:

import logginglogging.debug('This is debug message') #debuglogging.info('This is info message')  #infologging.warning('This is warning message') #warn

Print: WARNING: root: This is warning message on the screen

By default, logs at the WARNING level are printed.

  • DEBUG: detailed information and debugging information.
  • INFO: confirm that everything runs as expected.
  • WARNING: indicates an accident or a problem will occur in the near future (for example, 'disk full '). The software is still working normally.
  • ERROR: due to more serious problems, the software can no longer execute some functions.
  • CRITICAL: a serious error indicates that the software is no longer running.

2. Use the basicConfig function to configure the log input format and Method

import logginglogging.basicConfig(level=logging.DEBUG,  format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',  datefmt='%Y-%m-%d %a %H:%M:%S',  filename='test.log',  filemode='w') logging.debug('This is debug message')logging.info('This is info message')logging.warning('This is warning message')

The above Code does not print logs on the screen, but generates the test. log file in the current directory. The log is printed in the log file:

2017-10-16 Mon 10:05:17 testlogging. py [line: 25] DEBUG This is debug message

2017-10-16 Mon 10:05:17 testlogging. py [line: 26] INFO This is info message

2017-10-16 Mon 10:05:17 testlogging. py [line: 27] WARNING This is warning message

  • Parameters of the logging. basicConfig function:
  • Filename: Specifies the log file name.
  • Filemode: Same as the file function. It specifies the log file opening mode, 'w' or 'A'
  • Format: Specify the output format and content. format can output a lot of useful information, as shown in the preceding example:
% (Levelno) s: Print log level value % (levelname) s: Print Log Level name % (pathname) s: print the path of the current execution program, actually sys. argv [0] % (filename) s: print the current execution program name % (funcName) s: print the current function of the log % (lineno) d: current row number of the print log % (asctime) s: log printing time % (thread) d: Print thread ID % (threadName) s: Print thread name % (process) d: print process ID % (message) s: Print log information
  • Datefmt: specifies the time format, which is the same as time. strftime ()
  • Level: Set the log level. The default value is logging. WARNING.
  • Stream: Specifies the output stream of logs. You can specify the output stream to sys. stderr, sys. stdout or file, which is output to sys by default. stderr. When stream and filename are both specified, stream is ignored.

3. Simultaneously output logs to the screen and log files

# Define a StreamHandler to print the INFO-level or higher log information to a standard error and add it to the current log processing object console = logging. streamHandler () console. setLevel (logging. INFO) formatter = logging. formatter ('% (name)-12 s: % (levelname)-8 s % (message) s') console. setFormatter (formatter) logging. getLogger (''). addHandler (console)

Insert the code above to print logs on the screen at the same time.

Screen Printing:

Root: INFO This is info message

Root: WARNING This is warning message

Print in file:

2017-10-16 Mon 10:20:07 testlogging. py [line: 46] DEBUG This is debug message

2017-10-16 Mon 10:20:07 testlogging. py [line: 47] INFO This is info message

2017-10-16 Mon 10:20:07 testlogging. py [line: 48] WARNING This is warning message

4. Configure logs through the configuration file

# Logger. conf [loggers] # define the logger module. root is the parent class and must exist. Others are custom. Keys = root, infoLogger, warnlogger [logger_root] level = DEBUG # level, levels include DEBUG, INFO, WARNING, ERROR, CRITICALhandlers = infohandler, warnhandler # handlers processing class, there can be multiple logstores separated by commas (,). [logger_infoLogger] # [logger_xxxx] logger _ Module name handlers = infohandlerqualname = infoLogger # qualname logger name. The application uses logging. getLogger. For names that cannot be obtained, record them to the root module. Propagate = 0 # Whether propagate inherits the log information of the parent class, 0: No 1: yes [logger_warnlogger] handlers = warnhandlerqualname = warnloggerpropagate = 0 ############################# ################## define handler [handlers] keys = infohandler, warnhandler [handler_infohandler] class = StreamHandler # class handler class name level = INFO # level Log level formatter = form02 # formatter. The formatterargs defined below is (sys. stdout,) # args handler initialization function parameter [handler_warnhandler] class = FileHandlerlevel = WARNformatter = form01args = ('logs/deploylog. log', 'A ') ######################################## ######## define formatting output [formatters] keys = form01, form02 [formatter_form01] format = % (message) s % (asctime) sdatefmt = % Y-% m-% d % H: % M: % S [formatter_form02] format = % (asctime) s % (levelname) s % (message) sdatefmt = % Y-% m-% d % H: % M: % S

Log format

  • % (Asctime) s-month-day hour-minute-second, millisecond 20:10:43, 745
  • % (Filename) s file name, excluding the Directory
  • % (Pathname) s directory name, full path
  • % (FuncName) s function name
  • % (Levelname) s level name
  • % (Lineno) d row number
  • % (Module) s module name
  • % (Message) s message body
  • % (Name) s Log Module name
  • % (Process) d process id
  • % (ProcessName) s process name
  • % (Thread) d thread id
  • % (ThreadName) s thread name

Test Configuration File

from logging.config import fileConfigfileConfig('logger.conf')logger=logging.getLogger('infoLogger')logger.info('test1')logger_error=logging.getLogger('warnhandler')logger_error.warn('test5')

Summary

The above is all the content of this article. I hope the content of this article has some reference and learning value for everyone's learning or work. If you have any questions, please leave a message to us, thank you for your support.

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.