Python's Log logging module

Source: Internet
Author: User

1. Simply print the log to the screen
Import logging

Logging.debug (' This is Debug message ')

Logging.info (' This is Info message ')

Logging.warning (' This is warning message ')

<strong> on-screen printing: </strong><br/> WARNING:root:This is WARNING message

By default, logging prints the log to the screen with a log level of WARNING and a log-level size relationship: CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET, Of course, you can define the log level yourself.

2. Configure the output format and mode of the log by Logging.basicconfig function
Import logging

Logging.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 Debug message ')

Logging.info (' This is Info message ')

Logging.warning (' This is warning message ')

The contents of the <strong>./myapp.log file are: </strong><br/> Sun, 21:48:54 demo2.py[line:11] DEBUG this is Deb UG message<br/> Sun, 21:48:54 Demo2.py[line:12] Info This is INFO message<br/> Sun, 2009 21:48:54 Demo2.py[line:13] WARNING This is WARNING message

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:

% (Levelno) S: Print the value of the log level

% (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 name of the executing program

% (funcName) s: Print the current function of the log

% (Lineno) d: Print the current line number of the log

% (asctime) s: Time to print logs

% (thread) d: Print thread ID

% (threadname) s: Print thread name

% (process) d: Print process ID

% (message) s: Print log information

DATEFMT: Specify time format, same as Time.strftime ()

Level: Sets the log levels by default to logging. WARNING

Stream: 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 when stream and filename are specified simultaneously

3. Output logs to both file and screen at the same time
Import logging

Logging.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 ')

#################################################################################################

#定义一个StreamHandler, print 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) -12s:% (levelname) -8s% (message) s ')

Console.setformatter (Formatter)

Logging.getlogger ("). AddHandler (console)

#################################################################################################

Logging.debug (' This is Debug message ')

Logging.info (' This is Info message ')

Logging.warning (' This is warning message ')

<strong> on-screen printing: </strong><br/> root <wbr/> <wbr/> <wbr/> <wbr/> <wbr/> <wbr/> <wbr/>: info <wbr/> <wbr/> <wbr/> <wbr/> This is INFO message<br/&G T root <wbr /> <wbr /> <wbr /> <wbr /> <wbr /> <wbr /> <wbr /> : WARNING <wbr / > This is warning message

The contents of the <strong>./myapp.log file are: <br/> </strong>sun, 21:48:54 demo2.py[line:11] DEBUG this is Deb UG message<br/> Sun, 21:48:54 Demo2.py[line:12] Info This is INFO message<br/> Sun, 2009 21:48:54 Demo2.py[line:13] WARNING This is WARNING message

4.logging Log Rollback
Import logging
From logging.handlers import Rotatingfilehandler

#################################################################################################

#定义一个RotatingFileHandler, backup up to 5 log files, maximum 10M per log file

Rthandler = Rotatingfilehandler (' Myapp.log ', maxbytes=10*1024*1024,backupcount=5)

Rthandler.setlevel (Logging.info)

Formatter = logging. Formatter ('% (name) -12s:% (levelname) -8s% (message) s ')

Rthandler.setformatter (Formatter)

Logging.getlogger ("). AddHandler (Rthandler)

################################################################################################

As can be seen from the above example and in this example, logging has a main object of log processing, and other processing methods are added through AddHandler. Several handle methods of logging are as follows:

Logging. Streamhandler: Log output to stream, can be sys.stderr, sys.stdout, or file

Logging. Filehandler: Log output to File

Log rollback method, using Rotatingfilehandler and Timedrotatingfilehandler when actually used

Logging.handlers.BaseRotatingHandler

Logging.handlers.RotatingFileHandler

Logging.handlers.TimedRotatingFileHandler

Logging.handlers.SocketHandler: Remote output log to TCP/IP sockets

Logging.handlers.DatagramHandler: Remote output log to UDP sockets

Logging.handlers.SMTPHandler: Remote output log to e-mail address

Logging.handlers.SysLogHandler: Log Output to Syslog

Logging.handlers.NTEventLogHandler: Remote output log to Windows NT/2000/XP event log

Logging.handlers.MemoryHandler: Log output to in-memory development buffer

Logging.handlers.HTTPHandler: Remote output to HTTP server via "GET" or "POST"

Since Streamhandler and Filehandler are commonly used for log processing, they are included directly in the logging module, while others are included in the Logging.handlers module, see the python2.5 Manual for the use of the other processing methods described above.

5. Configuring logs via the Logging.config module
#logger. conf

###############################################

[Loggers]<br/> Keys=root,example01,example02

[logger_root]<br/> level=debug<br/> handlers=hand01,hand02

[logger_example01]<br/> handlers=hand01,hand02<br/> qualname=example01<br/> propagate=0

[logger_example02]<br/> handlers=hand01,hand03<br/> qualname=example02<br/> propagate=0

###############################################

[Handlers]<br/> Keys=hand01,hand02,hand03

[handler_hand01]<br/> class= "Streamhandler" <br/> level=info<br/> formatter=form02<br/> Args= (Sys.stderr,)

[handler_hand02]<br/> class= "Filehandler" <br/> level=debug<br/> formatter=form01<br/> args = (' Myapp.log ', ' a ')

[handler_hand03]<br/> class= "handlers". rotatingfilehandler<br/> level=info<br/> formatter=form02<br/> args= (' myapp.log ', ' a ', 10*1024* 1024, 5)

###############################################

[Formatters]<br/> keys=form01,form02

[Formatter_form01]<br/> format=% (asctime) s% (filename) s[line:% (lineno) d]% (levelname) s% (message) S<BR/ > datefmt=%a,%d%b%Y%h:%m:%s

[formatter_form02]<br/> format=% (name) -12s:% (levelname) -8s% (message) s<br/> datefmt=

In Example 3:

Import logging
Import Logging.config

Logging.config.fileConfig ("logger.conf") logger = Logging.getlogger ("example01")

Logger.debug (' This is Debug message ')

Logger.info (' This is Info message ')

Logger.warning (' This is warning message ')

In Example 4:

Import logging
Import Logging.config

Logging.config.fileConfig ("logger.conf") logger = Logging.getlogger ("Example02")

Logger.debug (' This is Debug message ')

Logger.info (' This is Info message ')

Logger.warning (' This is warning message ')

6.logging is thread-safe

Tagged:python

    • Related articles recommended:
    • Python Log printing feature learning
    • Some common features of the Python sys module
    • Python BeautifulSoup multithreaded parsing and crawling Web pages
    • This article from: Hobby Linux Technology Network
    • This article link: http://www.ahlinux.com/python/9106.html

Python's Log logging module

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.