Home Backend Development Python Tutorial python module learning logging

python module learning logging

Dec 17, 2016 pm 04:47 PM

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



Print on the screen:
WARNING:root:This is warning message

By default, logging prints the log to the screen, the log level is WARNING;
The log level size relationship is: CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET. Of course, you can also define the log level yourself.

2. Configure the log output format and method through the 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',
                   ', I filemode =' w ')
Logging.debug (' This is debug message ')
logging.info (' this is inco message ')
logging.warning (' this is warning m essage ') g



The content in the ./myapp.log file is:
Sun, 24 May 2009 21:48:54 demo2.py[line:11] DEBUG This is debug message
Sun, 24 May 2009 21:48:54 demo2.py[line :12] INFO This is info message
Sun, 24 May 2009 21:48:54 demo2.py[line:13] WARNING This is warning message


Parameters of logging.basicConfig function:

filename: Specify the log file name

filemode: It has the same meaning as the file function, specifying the opening mode of the log file, 'w' or 'a'
format: Specify the format and content of the output. format can output a lot of useful information, as shown in the above example:
%(levelno)s: Print the value of the log level
%(levelname)s: Print the log level name
%(pathname)s: Print the path of the currently executing program, which is actually sys.argv[0]
%(filename)s: Print the current executing program name
%(funcName)s: Print the current function of the log
%(lineno)d: Print the current line number of the log
%(asctime)s: Time to print log
%(thread)d: Print thread ID
%(threadName)s: Print thread name
%(PRocess)d: Print process ID
%(message)s: Print log information
datefmt: Specify the time format, the same as time.strftime()
level: Set the log level, the default is logging.WARNING
stream: Specify the output stream of the log. You can specify the output to sys.stderr, sys.stdout or a file. The default output is to sys.stderr. When stream and filename are specified at the same time, the stream is ignored. 3. Output the log to the file and file at the same time. Screen

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')######### ################################################ ######################################Define a StreamHandler to INFO level or higher Log information is printed to standard error and added 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')



Print on screen:
root : INFO This is info message
root : WARNING This is warning message

./myapp.log file The content is:
Sun, 24 May 2009 21:48:54 demo2.py[line:11] DEBUG This is debug message
Sun, 24 May 2009 21:48:54 demo2.py[line:12] INFO This is info message
Sun, 24 May 2009 21:48:54 demo2.py[line:13] WARNING This is warning message


4.logging log rollback

import loggingfrom logging.handlers import RotatingFileHandler######################################## ################################################# ######Define a RotatingFileHandler to back up up to 5 log files, each log file has a maximum of 10MRthandler = 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 this example, logging has a main object for log processing, and other processing methods are added through addHandler.
The several handle methods for logging are as follows:

logging.StreamHandler: The log is output to a stream, which can be sys.stderr, sys.stdout or a file. logging.FileHandler: The log is output to a file

Log rollback method. In actual use, RotatingFileHandler and TimedRotatingFileHandler are used logging.handlers.BaseRotatingHandler logging.handlers.RotatingFileHandler logging.handlers.TimedRotatingFileHandler

logging.handlers.SocketHandler: Remotely output logs to TCP/ip sockets

logging.handlers.DatagramHandler: Remote output logs to UDP sockets

logging.handlers.SMTPHandler: Remotely output logs to email address

logging.handlers.SysLogHandler: Log output to syslog

logging.handlers.NTEventLogHandler: Remotely output logs to the event log of Windows NT/2000/XP

logging.handlers.MemoryHandler: The log is output to the specified buffer in memory

logging.handlers.HTTPHandler: Remote output to HTTP server through "GET" or "POST"

Since StreamHandler and FileHandler are commonly used log processing methods, they are directly included in the logging module, while other methods are included in the logging.handlers module,
Above For other processing methods, please refer to the python2.5 manual!

5. Configure logs through the logging.config module

#logger.conf

############################## ############### [loggers]
keys=root,example01,example02

[logger_root]
level=DEBUG
handlers=hand01,hand02

[logger_example01]
handlers= hand01,hand02
qualname=example01
propagate=0

[logger_example02]
handlers=hand01,hand03
qualname=example02
propagate=0
################### ########################### [handlers]
keys=hand01,hand02,hand03

[handler_hand01]

class=StreamHandler
level=INFO
formatter=form02
args=(sys.stderr,)

[handler_hand02]class=FileHandler
level=DEBUG
formatter=form01
args=('myapp.log', 'a')

[ handler_hand03]class=handlers.RotatingFileHandler
level=INFO
formatter=form02
args=('myapp.log', 'a', 10*1024*1024, 5)
############ ################################# [formatters]
keys=form01,form02

[formatter_form01]
format=%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s
datefmt=%a, %d %b %Y %H:%M:% S

[formatter_form02]
format=%(name)-12s: %(levelname)-8s %(message)s
datefmt=
import loggingimport 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')
import loggingimport 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

The above is the content of learning logging in the python module. For more related articles, please pay attention to the PHP Chinese website (www.php .cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1503
276
How to use Python's built-in logging How to use Python's built-in logging May 10, 2023 am 10:55 AM

The main function of logging is to provide logging interfaces and numerous processing modules for users to store logs in various formats to help debug programs or record output information during program running. Logging log level The logging level is divided into five levels. The priorities from high to low are: **CRITICAL; **Serious program error**ERROR;**Program error/partial function error**WARNING;**The program has Possibility of errors **INFO;** Information when the program is running normally DEBUG Program debugging information The default log recording level is WARNING, that is, it will only be recorded when the log level is greater than or equal to WARNING. Commonly used records, etc.

How to solve Python's module cannot be read error? How to solve Python's module cannot be read error? Jun 24, 2023 am 11:48 AM

When writing Python code, we often need to import external modules. But sometimes there will be an error that the module cannot be read, which hinders our programming process. These errors generally have the following situations and solutions. Module is not installed or not added to the system path When we import a module, Python looks for the module in the system path. If the module is not installed or added to the system path, an unreadable error will occur. The solution is as follows: (1) Confirm whether the module has been installed. We can enter in the command line interface

How does Python's logging module provide a flexible framework for emitting log messages? How does Python's logging module provide a flexible framework for emitting log messages? Jun 05, 2025 am 12:13 AM

Python's logging module provides flexible logging capabilities through log levels, processors, formatting and hierarchical loggers. It supports five log levels (DEBUG, INFO, WARNING, ERROR, CRITICAL), allowing developers to classify information according to severity and control the output content by setting a global level; for example, only WARNING and above logs are displayed in production environments to keep it simple. In addition, logs can be sent to different targets, such as files, mails, or consoles by adding multiple processors, each processor can independently configure levels and formats; for example, one processor writes all DEBUG and above logs to a file, and the other displays WA only in the console

How to deal with the java underlying JDK Logging module How to deal with the java underlying JDK Logging module May 10, 2023 pm 02:55 PM

Starting from the example, the use of JDKLogging is very simple. As shown in the following code, you can first use the static method getLogger of the Logger class to obtain a logger, and then you can use the obtained logger for log input anywhere. For example, calls like logger.info("Mainrunning."). packagecom.bes.logging;importjava.util.logging.Level;importjava.util.logging.Logger;publicclassLoggerTest{pr

How to use python's logging library How to use python's logging library May 16, 2023 pm 06:07 PM

Logging is a module in the Python standard library for logging. It provides a simple but flexible way to record events in your program for later debugging and analysis. The basic steps for using the logging library are as follows: import logging library importlogging configuration logger logging.basicConfig(level=logging.INFO,format='%(asctime)s-%(name)s-%(levelname)s-%(message )s')The above code configures a basic logger, specifying the logging level

What module is commonly used to create arrays in Python? What module is commonly used to create arrays in Python? May 05, 2025 am 12:02 AM

ThemostcommonlyusedmoduleforcreatingarraysinPythonisnumpy.1)Numpyprovidesefficienttoolsforarrayoperations,idealfornumericaldata.2)Arrayscanbecreatedusingnp.array()for1Dand2Dstructures.3)Numpyexcelsinelement-wiseoperationsandcomplexcalculationslikemea

How to solve Python's module not installed error? How to solve Python's module not installed error? Jun 25, 2023 pm 05:52 PM

Python is a powerful programming language commonly used in fields such as data analysis, machine learning, and web development. In the process of using Python, we often need to use various third-party modules to extend Python's functions. However, if we encounter a "module not installed" error when using Python, this will affect our work efficiency and development progress. This article will explain how to solve Python's module not installed error. Installing pippip is Python’s own package manager, which can be easily

An article will guide you through the logging module in Python An article will guide you through the logging module in Python Jul 25, 2023 pm 02:04 PM

This article takes the basics of Pythonl as an example, mainly introduces the basic usage of the logging module, as well as the problems encountered in real-life applications, and provides detailed answers.

See all articles