Python Logging class Library use example _python

Source: Internet
Author: User
Tags glob log log syslog

First, simple use

Copy Code code as follows:

Def testlogbasic ():
Import logging
Logging.basicconfig (filename = ' Log.txt ', FileMode = ' a ', level = logging. NOTSET, format = '% (asctime) s-% (levelname) s:% (message) s ')
Logging.debug (' This are a message ')
Logging.info ("This is a info")
Logging.disable (#logging). WARNING
Logging.warning ("This is a warnning")
Logging.critical ("This is a critical issue")
Logging.error ("This is a error")
Logging.addlevelname ("Mycustomerror")
Logging.log ("This is a My custom error")
Try
Raise Exception (' This is a Exception ')
Except
Logging.exception (' exception ')
Logging.shutdown ()

Testlogbasic ()

Description: (This instance is the simplest use for logging log to log files)

1 The default log to Log.txt,log file defined in Logging.basicconfig () is append mode, and the format for handling all logging,log with level greater than logging.notset is defined as '% ' (asctime ) S-% (levelname) s:% (message) s ';

2 use Logging.debug () ... Log the corresponding level log;

3) using logging.disable () to disable a logging level;

4 use Logging.addlevelname to increase custom logging level;

5 use Logging.log to log the logging level log of the custom;

The output of the text log is as follows:

Copy Code code as follows:

2011-01-18 10:02:45,415-debug:this is a message
2011-01-18 10:02:45,463-info:this is a INFO
2011-01-18 10:02:45,463-critical:this is a CRITICAL issue
2011-01-18 10:02:45,463-error:this is a ERROR
2011-01-18 10:02:45,463-mycustomerror:this is a My custom error
2011-01-18 10:02:45,463-error:exception
Traceback (most recent call last):
File "testlog.py", line, in Testlogbasic
Raise Exception (' This is a Exception ')
Exception:this is a Exception

Second, the level of logging

Copy Code code as follows:

#logging level
#logging. NOTSET 0
#logging. DEBUG 10
#logging. INFO 20
#logging. WARNING 30
#logging. ERROR 40
#logging. CRITICAL 50

The level of the logging corresponds to an int, such as 10,20 ... users can customize the level of logging.

You can use Logging.setlevel () to specify the level of logger to be processed, such as my_logger.setlevel (logging. DEBUG) represents a logging that handles only logging with a level greater than 10.

Third, handlers

Handler defines how log is stored and displayed.

Nullhandler don't do anything.

The Streamhandler instance sends an error to the stream (an object similar to the file).
The Filehandler instance sends an error to the disk file.
Baserotatinghandler is the base class for all round sacrifice logs and cannot be used directly. But you can use Rotatingfilehandler and Timerotatingfilehandler.
The Rotatingfilehandler instance sends information to the disk file and restricts the maximum log file size, and sacrifice in due time.
The Timerotatingfilehandler instance sends an error message to the disk and rounds the sacrifice at the appropriate event interval.
Sockethandler instance sends log to TCP/IP socket.
The Datagramhandler instance sends an error message through the UDP protocol.
Smtphandler instance sends an error message to a specific email address.
The Sysloghandler instance sends logs to the UNIX syslog service and supports remote Syslog services.
The Nteventloghandler instance sends logs to the WINDOWSNT/2000/XP event log.
The Memoryhandler instance sends logs into an in-memory buffer and empties when certain conditions are reached.
The HttpHandler instance sends an error message to the HTTP server through a GET or post method.
The Nullhandler,streamhandler and Filehandler classes are defined in the core logging module. Other handler are defined in each child module, called Logging.handlers.

There is, of course, a logging.config module that provides configuration functionality.

Four, Filehandler + Streamhandler

Copy Code code as follows:

Def testhanderandformat ():
Import logging
Logger = Logging.getlogger ("simple")
Logger.setlevel (logging. DEBUG)

# Create file handler which logs even debug messages
FH = logging. Filehandler ("Simple.log")
Fh.setlevel (logging. DEBUG)

# Create console handler with a higher log level
ch = logging. Streamhandler ()
Ch.setlevel (logging. ERROR)

# Create formatter and add it to the handlers
Formatter = logging. Formatter ("% (asctime) s-% (name) s-% (levelname) s-% (message) s")
Ch.setformatter (Formatter)
Fh.setformatter (Formatter)

# Add the handlers to logger
Logger.addhandler (CH)
Logger.addhandler (FH)

# "Application" code
Logger.debug ("Debug Message")
Logger.info ("info message")
Logger.warn ("Warn message")
Logger.error ("error message")
Logger.critical ("critical Message")

Testhanderandformat ()

Description: (this instance uses both Filehandler and Streamhandler to simultaneously write log to file and console)

1) use Logging.getlogger () to create a new named logger;

2) using logging. Filehandler () to generate Filehandler to write log log file, using Logger.addhandler () will handler and logger binding;

3) using logging. Streamhandler () to generate Streamhandler to write log to console, use Logger.addhandler () to bind handler with logger;

4) using logging. Formatter () to construct an instance of log format, using Handler.setformatter () to bind Formatter with handler;

Run results

Simple.txt

Copy Code code as follows:

2011-01-18 11:25:57,026-simple-debug-debug Message
2011-01-18 11:25:57,072-simple-info-info Message
2011-01-18 11:25:57,072-simple-warning-warn Message
2011-01-18 11:25:57,072-simple-error-error Message
2011-01-18 11:25:57,072-simple-critical-critical Message

Console

Copy Code code as follows:

2011-01-18 11:25:57,072-simple-error-error Message
2011-01-18 11:25:57,072-simple-critical-critical Message

Five, Rotatingfilehandler

Copy Code code as follows:

Def testrotating ():
Import Glob
Import logging
Import Logging.handlers

Log_filename = ' Logging_rotatingfile_example.out '

# Set up a specific logger with our desired output level
My_logger = Logging.getlogger (' MyLogger ')
My_logger.setlevel (logging. DEBUG)

# ADD The log message handler to the logger
Handler = Logging.handlers.RotatingFileHandler (Log_filename, maxbytes=20, backupcount=5)

My_logger.addhandler (Handler)

# Log Some messages
For I in range (20):
My_logger.debug (' i =%d '% i)

# What files are created
LogFiles = Glob.glob ('%s* '% log_filename)

For filename in logfiles:
Print (filename)

Testrotating ()

Description

Rotatingfilehandler Specifies the maximum size of a single log file and the maximum number of log files, if the file is greater than the maximum, will be split into multiple files, if the number of log files more than the maximum number, the oldest log file will be deleted. For example, the latest log in this example always contains the oldest log in the logging_rotatingfile_example.out,logging_rotatingfile_example.out.5.

Run Result:

Copy Code code as follows:

Logging_rotatingfile_example.out
Logging_rotatingfile_example.out.1
Logging_rotatingfile_example.out.2
Logging_rotatingfile_example.out.3
Logging_rotatingfile_example.out.4
Logging_rotatingfile_example.out.5

Vi. use of fileconfig to use logger

Copy Code code as follows:

Import logging
Import Logging.config

Logging.config.fileConfig ("logging.conf")

# Create Logger
Logger = Logging.getlogger ("Simpleexample")

# "Application" code
Logger.debug ("Debug Message")
Logger.info ("info message")
Logger.warn ("Warn message")
Logger.error ("error message")
Logger.critical ("critical Message")

logging.conf files are as follows:

Copy Code code as follows:

[Loggers]
Keys=root,simpleexample

[Handlers]
Keys=consolehandler

[Formatters]
Keys=simpleformatter

[Logger_root]
Level=debug
Handlers=consolehandler

[Logger_simpleexample]
Level=debug
Handlers=consolehandler
Qualname=simpleexample
Propagate=0

[Handler_consolehandler]
Class=streamhandler
Level=debug
Formatter=simpleformatter
Args= (Sys.stdout,)

[Formatter_simpleformatter]
format=% (asctime) s-% (name) s-% (levelname) s-% (message) s
datefmt=

Run Result:

Copy Code code as follows:

2005-03-19 15:38:55,977-simpleexample-debug-debug Message
2005-03-19 15:38:55,979-simpleexample-info-info Message
2005-03-19 15:38:56,054-simpleexample-warning-warn Message
2005-03-19 15:38:56,055-simpleexample-error-error Message
2005-03-19 15:38:56,130-simpleexample-critical-critical Message

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.