Python Logging module Learning (GO)

Source: Internet
Author: User
Tags virtualenv

Objective

The log is very important and has recently come into contact with this, so the system looks at the use of Python's module. This article is an introduction to the usage of the logging module, the main reference article is the official Python document, the link to see the reference list.

In addition, Python's HowTos document is very detailed, how to write in a few days, so the students with English reading ability suggested to read.

Logging module composition

Mainly divided into four parts:

    • Loggers: Provides an interface that the application uses directly
    • Handlers: Upload loggers generated logs to the specified location
    • Filters: Filtering the output log
    • Formatters: Control output format
Log level Level When
Numeric Valueit ' s used
DEBUG 10 Detailed information, typically of interest only when diagnosing problems.
INFO 20 Confirmation that things is working as expected.
WARNING 30 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 40 Due to a more serious problem, the software have not been able to perform some function.
CRITICAL 50 A serious error, indicating the program itself is unable to continue running.
Noset 0 GetAttr (Logging, loglevel.upper ())

The default level is warning, which can be recorded by printing to the screen or recorded in a file.

Module using a sample simple example print output
In [5]: import loggingIn [6]: logging.warning("FBI warning")WARNING:root:FBI warningIn [7]: logging.info("information")# 没有打印是因为默认级别是warning
Output to File
in [4]: Import loggingin [5]: Logging.basicconfig (filename=' Example.log ', level=logging. DEBUG)in [6]: Logging.debug ("Debug")in [7]: logging.warning (' Warning ')in [8]: Logging.info (' Info ')in [9]: lsc++ stl/a.py example.log parser/test.sh*in [Ten]: Cat Example.logDEBUG:root:debugWARNING:root:warningINFO:root:infoin [+]: logging.warning (' New warning ')Note that this is added directly to the back, that is, add, if you want to overwrite the content can change the way the file is writtenin [[]: Cat example.logDEBUG:root:debugWARNING:root:warningINFO:root:infoWARNING:root:New warning# Overwrite the way to write the example (test)? Test ipythonwarning:attemptingTo workIn a virtualenv.If you encounter problems, please install IPython inside the virtualenv. Python2.7.11 (Default, June172016,20:01:Wuyi) Type"Copyright","Credits"Or"License"For more information. IPython4.2.0--an enhanced Interactive Python.? Introductionand overviewof IPython' s features.%quickref, Quick reference.help, Python' s own Help system.Object? Details about' Object ', use ' object? ' for extra details.in [1]: Import loggingin [2]: Logging.basicconfig (filename=' Example.log ', filemode= ' W ', level=logging. DEBUG)in [3]: logging.warning (' FBI warning ')in [4]: lsc++ stl/a.py example.log parser/test.sh*in [5]: Cat Example.logWARNING:root:FBI Warningin [6]: Quit (test)? Test ipythonwarning:attemptingTo workIn a virtualenv.If you encounter problems, please install IPython inside the virtualenv. Python2.7.11 (Default, June172016,20:01:Wuyi) Type"Copyright","Credits"Or"License"For more information. IPython4.2.0--an enhanced Interactive Python.? Introduction and Overview of ipython ' s features.%quickref-Quick Reference.help-Python ' s own Help System. Object? Details about  In [1]: Import loggingin [2]: Logging.basicconfig (Filename= ' Example.log ', filemode= ' W ', level=logging. DEBUG) in [3]: logging.warning (in [4]: Cat example.logWARNING:root:warning  
Use of variables

The print same as using variables in statements such as:

In [5]: logging.warning(‘%s before you %s‘, ‘Look‘, ‘leap!‘)In [6]: cat example.logWARNING:root:warningWARNING:root:Look before you leap!
Output format

Can be basicConfig set in, parameter name can see link, can set the time what, such as:

In [2]: import loggingIn [3]: logging.basicConfig(format=‘%(asctime)s:%(levelname)s:%(message)s‘, level=logging.DEBUG)In [4]: logging.warning(‘And this, too‘)2016-12-06 15:40:43,577:WARNING:And this, too
Advanced use

When you want to use the logging module in the project must not be in such a sentence to write, it is generally possible to abstract a module, which is more effective. The logging module provides four classes (loggers,formatters,filtters,handlers) to implement different functions, and in this case we want to encapsulate a function, we need to customize for these functions.

If you want to customize the idea is also very simple, first instantiate a corresponding object, and then make some settings, you can simply look at the following example:

Import logging#Create Loggerlogger =Logging.getlogger (' Simple_example ') logger.setlevel (Logging. DEBUG) #Create consoleHandlerandSetLevelto DEBUGCH =Logging. Streamhandler () Ch.setlevel (Logging. DEBUG) #Create Formatterformatter =Logging. Formatter ('% (asctime) s-% (name) s-% (levelname) s-% (message) s ') #Add FormatterTo Chch.setformatter (formatter) #Add CHTo Loggerlogger.addhandler (CH) #' Application ' Codelogger.debug (' Debug message ') Logger.info (' Info message ') Logger.warn (' Warn message ') logger.Error' Error message ') logger.Critical' Critical message ') # output is: $ python simple_logging_module.py2005-03-1915:10:26,618-simple_example-debug-debug message2005-03-1915:10:26,620-simple_example-info-info message2005-03-19 15: 10: 26,695-simple_example-WARNING- Warn Message2005-03-19 15:10:26,697- Simple_example-error-error message 2005-03-19 15:10:26, 773-simple_example-critical- Critical message              
Import configuration from configuration file

Module content:

Import Loggingimport Logging.configlogging.config.fileConfig (' logging.conf ')# Create Loggerlogger = Logging.getlogger (' Simpleexample ')# ' Application ' Codelogger.Debug' Debug message ') logger.Info' Info message ') logger.Warn' Warn message ') logger.Error' Error message ') logger.critical (' Critical message ')# Output $ python simple_logging_config.py2005-13L1915:38:45M977-simpleexample-debug-Debug message2005-13L1915:38:45M979-simpleexample-info-Info message2005-03- :$,054-simpleexample-warning- warn message2005-03-  : 055-simpleexample-error- ERROR message2005-03- :  A:130-simpleexample-critical-critical message        

Configuration file Contents:

[Loggers]Keys=root,simpleexample[Handlers]keys=consolehandler[formatters]keys =simpleformatter[logger_root]level=debug handlers=consolehandler[logger_simpleexample] level=debughandlers=consolehandler Qualname=simpleexamplepropagate=0 [Handler_consolehandler] class=streamhandlerlevel=debug Formatter=simpleformatterargs= (Sys.stdout,) [formatter_ Simpleformatter]format=% (asctime) s-% (name) s-% (levelname) s-% (message) s    

You can also use a YAML-formatted configuration file, such as:

version: 1 Formatters: Simple: format:  "% (Asctime) S-% (name) s-% (levelname) s-% (message) s ' handlers: Console: class:logging. Streamhandler Level:debug formatter:simple  Stream:ext://sys.stdoutloggers: Simpleexample: Level:debug handlers: [Console]  propagate: noroot:  Level:debug handlers: [console]       
Ps

Logging module use will also have a lot of pits, common is the issue of duplicate printing log, you can search, here are some links for reference:

    1. http://www.jianshu.com/p/25f70905ae9d
    2. Https://yinzo.github.io/14610807170718.html
    3. http://python.jobbole.com/86887/
Reference
    1. Https://docs.python.org/2/library/logging.html
    2. Https://docs.python.org/2/howto/logging.html#logging-basic-tutorial

Transfer from http://www.cnblogs.com/wswang/p/6138304.html

Python Logging module Learning (GO)

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.