Python Log module logging

Source: Internet
Author: User
Module-level functions

Logging.getlogger ([name]): Returns a Logger object that returns root if no name is specified logger

Logging.debug (), Logging.info (), logging.warning (), Logging.error (), logging.critical (): Set the log level for root logger

Logging.basicconfig (): Establishes a streamhandler for the logging system with the default formatter, sets the base configuration and adds it to root logger

Logger

Logging.getlogger ([name])

Returns a logger instance that returns root logger if no name is specified.

Each program obtains a logger before outputting the information. Logger usually corresponds to the program's module name, such as the chat tool's graphical interface module can get its logger:

Log=logging.getlogger ("Chat.gui")

And the core module can do this:

Log=logging.getlogger ("Chat.kernel")

Logger.setlevel (logging. WARNING): Specifies the lowest log level, and the level below WARNING is ignored

Logger.addfilter (filt), Logger.removefilter (filt): Add or remove the specified filter

Logger.addhandler (HDLR), Logger.removehandler (HDLR): Add or remove the specified handler

Handlers

The handler object is responsible for sending relevant information to the specified destination. Can be file, screen, network, socket, etc.

Handler.setlevel (LEL): Specifies the level of information being processed, and information below the LEL level is ignored

Handler.setformatter (): Select an output format for this Handler

Handler.addfilter (filt), Handler.removefilter (filt): Add or remove a filter object

Log Print to screen

Import Logginglogging.debug (' This was debug message ') Logging.info (' This is Info message ') logging.warning (' This is Warning message ') return: WARNING:root:This is warning message print to screen

By default, logging prints the log to the screen with a log level of warning;
Log level size relationships are: CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET, and of course you can define the log level yourself.

Format Log Output

Parameters of the Logging.basicconfig function:
FileName: Specify the log file name
FileMode: Same as file function, specify open mode of log file, ' W ' or ' a '
Format: Specifies the formats and contents of the output, format can output a lot of useful information, as in the example above:

Import Logginglogging.basicconfig (level=logging. DEBUG,                format= '% (asctime) s% (filename) s[line:% (lineno) d]% (levelname) s% (message) s ',                datefmt= '%a,%d%b%Y%H :%m:%s ',                filename= ' Myapp.log ',                filemode= ' W ')    logging.debug (' This is the Debug message ') Logging.info (' This  is Info message ') logging.warning (' This is warning message '). The contents of the/myapp.log file are: Sun, May 21:48:54 Demo2.py[line:11]  Debug this was debug Messagesun, 21:48:54 Demo2.py[line:12] Info This is info Messagesun, 2009 21:48:54 DEMO2.PY[LINE:13] WARNING This is WARNING message modify output format

Log format variables

% (Levelno) S: Print log level value% (levelname) S: Print log level name% (pathname) s: Prints the path of the currently executing program, which is actually sys.argv[0]% (filename) s: Prints the current executing program name% ( FuncName) S: Print log current function% (Lineno) d: Print log current line number% (asctime) s: Time to print log% (thread) d: Print thread ID% (threadname) s: Print thread name% (process) d: Hit Imprint Process ID% (message) s: Print log information datefmt: Specifies the time format, same as Time.strftime () level: Sets the log levels by default to logging. Warningstream: Specifies the output stream that will log, can specify output to Sys.stderr,sys.stdout or file, default output to Sys.stderr, stream is ignored in log format when stream and filename are specified simultaneously

Logging method

Logging. Streamhandler: Log output to stream, can be sys.stderr, sys.stdout or file Logging.filehandler: Log output to file log rollback mode, Use Rotatingfilehandler and TimedRotatingFileHandlerlogging.handlers.BaseRotatingHandlerlogging.handlers.RotatingFileHandle in real time Rlogging.handlers.TimedRotatingFileHandlerlogging.handlers.SocketHandler: Remote output log to TCP/IP Socketslogging.handlers.DatagramHandler:  remote output log to UDP Socketslogging.handlers.SMTPHandler:  Remote output log to mail address Logging.handlers.SysLogHandler: Log output to Sysloglogging.handlers.NTEventLogHandler: remote output log to Windows Nt/2000/ XP Event Log Logging.handlers.MemoryHandler: Log output to in-memory development bufferlogging.handlers.HTTPHandler: Via "GET" or "POST" Remote output to HTTP server logging method

Because Streamhandler and filehandler are common log processing methods, they are included directly in the logging module, while others are included in the Logging.handlers module

Defining the Log module in the program

Import logging# Create Loggerdef Logger (log_type): Logger = Logging.getlogger (log_type) # Creating Logger object, type ' Test-log ' Logger.setlevel (logging. WARNING) # Sets the lowest log level, which overrides the level of CH and FH # Create output to the console handler, and set the level to DEBUGCH = logging. Streamhandler () Ch.setlevel (logging. DEBUG) # Control the output to the level of the screen # Create a handler for output to a file and set the level of FH = logging. Filehandler ("Access.log") fh.setlevel (logging. WARNING) # Create log format Formatter_stream = logging. Formatter ('% (name) s-% (levelname) s-% (message) s ') Formatter_file = logging. Formatter ('% (asctime) s-% (name) s-% (levelname) s-% (message) s ') # Add Formatter to CH and fhch.setformatter (formatter_str EAM) Fh.setformatter (formatter_file) # Add ch and fh to Loggerlogger.addhandler (CH) logger.addhandler (FH) return Loggereee = Logger (' EEE ') RRR = logger (' RRR ') rrr.debug (' Debug Message ') Rrr.info (' info message ') rrr.warning (' Warn Message ') Eee.error (' Error message ') eee.critical (' critical message ') code

Screen display content

Rrr-info-info message

Rrr-warning-warn message

Eee-error-error message

Eee-critical-critical message

Content in Files

2017-02-21 21:35:05,700-rrr-warning-warn Message

2017-02-21 21:35:05,700-eee-error-error Message

2017-02-21 21:35:05,700-eee-critical-critical Message


Filter filters

When you call Logging.getlogger (), the format of the parameter is similar to "A.B.C". This is done in order to configure the filter. After the filter is added, the log is processed by the filter before the output

Filter "AAA. BBB "only gives name to" AAA. BBB "Beginning of logger output information

Multiple filters can be added, and the log will not output as long as one filter is rejected

Import Loggingdef Logger (log_type): Logger = Logging.getlogger (log_type) # Create Logger object, type is ' Test-log ' Logger.setlevel ( Logging. DEBUG) # This level overrides the level of CH and FH # Create output to the console handler and set the level to DEBUGCH = logging. Streamhandler () Ch.setlevel (logging. DEBUG) # Control output to screen level # set filter = logging. Filter (' AAA. Bbb. CCC ') Ch.addfilter (filter) Formatter_stream = logging. Formatter ('% (name) s-% (levelname) s-% (message) s ') Ch.setformatter (formatter_stream) Logger.addhandler (CH) # CH joins Loggerreturn loggereee = Logger (' AAA. BBB.CCC ') RRR = Logger (' AAA. Bbb. DDD ') rrr.error (' Debug Message ') Rrr.error (' info message ') Eee.error (' critical message ') Eee.error (' Critical message ') Code

Cutting logs

Cut by size

Import loggingfrom Logging Import handlers# Create Loggerdef Logger (log_type): Logger = Logging.getlogger (Log_type) Logger.setlevel (logging. DEBUG) fh = logging. Filehandler ("Access.log") fh.setlevel (logging. WARNING) # cut log file by Time FH = handlers. Timedrotatingfilehandler (filename= ' Access.log ', when= ' s ', interval=10) Formatter_file = logging. Formatter ('% (asctime) s-% (name) s-% (levelname) s-% (message) s ') Fh.setformatter (formatter_file) Logger.addhandler (FH ) Return loggerrrr = Logger (' AAA. Bbb. DDD ') rrr.error (' Debug Message ') Rrr.error (' info message ') rrr.error (' warn message ') code

Interval: Time interval

When: Time unit s seconds M min h hours D days W per week (Interval==0 on behalf of Monday) midnight every morning

About root logger and logger's parent-child relationship

The previous mentions of root logger, in fact logger instances there is a parent-child relationship, root logger is the topmost logger, it is all logger ancestors. such as: Root logger is the default logger if you do not create logger instances, call Logging.debug (), Logging.info () logging.warning (), Logging.error (), Logging.critical () These functions, the logger used is root logger, which can be created automatically and is a single instance.


How to get root logger by Logging.getlogger () or Logging.getlogger ("") to get the root logger instance.
The default Levelroot logger default level is logging. WARNING
How to represent the name of a parent-child relationship logger can represent a parent-child relationship between logger. For example: Parent_logger = Logging.getlogger (' foo ') Child_logger = Logging.getlogger (' Foo.bar ')
What is effective Levellogger has a concept called effective level. If a logger does not display the level, then it uses the level of the father. If the father does not display the level, just use the father's level to push .... At the end of the root logger, you must set the level. The default is logging. Warningchild loggers Gets the message, both the message is distributed to its handler processing, and it is passed to all ancestors logger processing

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.