Python Logging Module Learning notes

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

Example: logging_level_example.py

The code is as follows:


Import logging
Import Sys

levels = {' Debug ': Logging. DEBUG,
' Info ': Logging.info,
' Warning ': Logging. WARNING,
' ERROR ': Logging. ERROR,
' Critical ': logging. CRITICAL}

If Len (SYS.ARGV) > 1:
Level_name = sys.argv[1]
Level = Levels.get (level_name, logging. NOTSET)
Logging.basicconfig (Level=level)

Logging.debug (' This is a debug message ')
Logging.info (' This was an info message ')
Logging.warning (' This is a warning message ')
Logging.error (' This was an error message ')
Logging.critical (' This is a critical error message ')


Output:

The code is as follows:


$ python logging_level_example.py Debug
DEBUG:root:This is a debug message
INFO:root:This is an info message
WARNING:root:This is a WARNING message
ERROR:root:This is an error message
CRITICAL:root:This is a CRITICAL error message

$ python logging_level_example.py Info
INFO:root:This is an info message
WARNING:root:This is a WARNING message
ERROR:root:This is an error message
CRITICAL:root:This is a CRITICAL error message

Loggers

Logger.setlevel (LEL): Specifies the lowest log level, and the level below LEL is ignored. Debug is the lowest built-in level, critical is the highest
Logger.addfilter (filt), Logger.removefilter (filt): Add or remove the specified filter
Logger.addhandler (HDLR), Logger.removehandler (HDLR): Add or remove the specified handler
Logger.debug (), Logger.info (), logger.warning (), Logger.error (), logger.critical (): Log levels you can set

Example: simple_logging_module.py

The code is as follows:


Import logging

# Create Logger
Logger = Logging.getlogger ("Simple_example")
Logger.setlevel (logging. DEBUG)

# Create console handler and set level to debug
ch = logging. Streamhandler ()
Ch.setlevel (logging. DEBUG)

# Create Formatter
Formatter = logging. Formatter ("% (asctime) s-% (name) s-% (levelname) s-% (message) s")

# Add Formatter to Ch
Ch.setformatter (Formatter)

# Add CH to Logger
Logger.addhandler (CH)

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


Output:

The code is as follows:


$ python simple_logging_module.py
2005-03-19 15:10:26,618-simple_example-debug-debug Message
2005-03-19 15:10:26,620-simple_example-info-info Message
2005-03-19 15:10:26,695-simple_example-warning-warn Message
2005-03-19 15:10:26,697-simple_example-error-error Message
2005-03-19 15:10:26,773-simple_example-critical-critical Message

Handlers

The handler object is responsible for sending relevant information to the specified destination. Multiple handler can be added through the AddHandler () method
Handler.setlevel (LEL): Specifies the level of information being processed, and information below the LEL level is ignored
Handler.setformatter (): Choose a format for this Handler
Handler.addfilter (filt), Handler.removefilter (filt): Add or remove a filter object

Formatters

The formatter object sets the final rules, structure, and contents of the log information, the default time format is%y-%m-%d%h:%m:%s, and the following are some of the information commonly used by formatter

% (name) s

Logger's name.

% (Levelno) s

Log level in digital form

% (LevelName) s

Log level in text form

% (pathname) s

The full path name of the module that called the log output function may not have

% (filename) s

The file name of the module that called the log output function

% (module) s

Call the module name of the log output function

% (FuncName) s

Function name of the call log output function

% (Lineno) d

The line of code where the statement that called the log output function is located

% (created) f

Current time, represented by the UNIX standard floating-point number representing the time

% (relativecreated) d

The number of milliseconds since logger was created when the log information is output

% (Asctime) s

The current time in string form. The default format is "2003-07-08 16:49:45,896". The comma is followed by milliseconds

% (thread) d

The thread ID. Probably not.

% (ThreadName) s

The name of the thread. Probably not.

% (process) d

The process ID. Probably not.

% (message) s

User-Output messages


Finally, here's a complete example:

The code is as follows:


Import logging

# Set up logging to File-see previous sections for more details
Logging.basicconfig (level=logging. DEBUG,
format= '% (asctime) s% (name) -12s% (levelname) -8s% (message) s ',
datefmt= '%m-%d%h:%m ',
Filename= '/temp/myapp.log ',
Filemode= ' W ')
# define a Handler which writes INFO messages or higher to the Sys.stderr
console = logging. Streamhandler ()
Console.setlevel (Logging.info)
# set a format which is simpler to console use
Formatter = logging. Formatter ('% (name) -12s:% (levelname) -8s% (message) s ')
# tell the handler to use this format
Console.setformatter (Formatter)
# Add the handler to the root logger
Logging.getlogger ("). AddHandler (console)

# Now, we can log to the root logger, or any other logger. First the root ...
Logging.info (' Jackdaws love my big sphinx of quartz. ')

# Now, define a couple of all loggers which might represent areas in your
# application:

Logger1 = Logging.getlogger (' myapp.area1 ')
Logger2 = Logging.getlogger (' myapp.area2 ')

Logger1.debug (' Quick zephyrs blow, vexing daft Jim. ')
Logger1.info (' How quickly daft jumping zebras vex. ')
Logger2.warning (' Jail Zesty vixen who grabbed pay from quack. ')
Logger2.error (' The five boxing wizards jump quickly. ')

After running, see the results at the terminal

The code is as follows:


Root:info jackdaws Love My big sphinx of quartz.
Myapp.area1:INFO how quickly daft jumping zebras vex.
Myapp.area2:WARNING Jail Zesty Vixen who grabbed pay from quack.
Myapp.area2:ERROR the five boxing wizards jump quickly.

Results in the log file

The code is as follows:


10-22 22:19 root INFO jackdaws love my big sphinx of quartz.
10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
10-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.
10-22 22:19 myapp.area2 WARNING Jail Zesty Vixen who grabbed pay from quack.
10-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly.


Debug information found only in the file, this is because Streamhandler SetLevel is info, you can see the difference between Logger.setlevel () and Handler.setlevel ()

For more information, see http://docs.python.org/library/logging.html

  • 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.