


What is the use of the logging module in python? Introduction to the usage of logging module
This article brings you what is the use of the logging module in python? The usage introduction of the logging module has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
The logging module is a built-in module that comes with pyhton, providing a standard logging interface
Log level list
logger: generate logs Object
Filter: object for filtering logs
Handler: receives logs and controls printing to different places. FileHandler is used to print to files, StreamHandler is used to print to terminals
Formatter: different logs can be customized format object, and then bind it to different Handler objects to control the log formats of different Handlers
Code examples of how to use several objects:
'''critical=50 error =40 warning =30 info = 20 debug =10''' import logging #1、logger对象:负责产生日志,然后交给Filter过滤,然后交给不同的Handler输出logger=logging.getLogger(__file__) #2、Filter对象:不常用,略 #3、Handler对象:接收logger传来的日志,然后控制输出h1=logging.FileHandler('t1.log') #打印到文件h2=logging.FileHandler('t2.log') #打印到文件h3=logging.StreamHandler() #打印到终端 #4、Formatter对象:日志格式formmater1=logging.Formatter('%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S %p',) formmater2=logging.Formatter('%(asctime)s : %(message)s', datefmt='%Y-%m-%d %H:%M:%S %p',) formmater3=logging.Formatter('%(name)s %(message)s',) #5、为Handler对象绑定格式h1.setFormatter(formmater1) h2.setFormatter(formmater2) h3.setFormatter(formmater3) #6、将Handler添加给logger并设置日志级别logger.addHandler(h1) logger.addHandler(h2) logger.addHandler(h3) logger.setLevel(10) #7、测试logger.debug('debug') logger.info('info') logger.warning('warning') logger.error('error') logger.critical('critical')
Note: The log will be The logger first filters once and then to the Handler object. When the Handler object and the logger object set the log level at the same time, the final log level will be set according to the highest level of the two.
Can be used in the logging.basicConfig() function The default behavior of the logging module can be changed through specific parameters. The available parameters are
filename: Create a FiledHandler with the specified file name, so that the log will be stored in the specified file
filemode: The file opening method, when filename is specified When using this parameter, the default value is "a" and can also be specified as "w".
format: Specify the log display format used by the handler
datefmt: Specify the date and time format
level: Set the log level of the rootlogger
stream: Create a StreamHandler with the specified stream. You can specify the output to sys.stderr, sys.stdout or a file. The default is sys.stderr. If both filename and stream parameters are listed at the same time, the stream parameter will be ignored.
Format string that may be used in the format parameter:
%(name)s Logger’s name
%(levelno)s The log level in numerical form
%(levelname)s The log level in text form
%(pathname)s The completeness of the module that calls the log output function Path name, may not have
%(filename)s The file name of the module that calls the log output function
%(module)s The module name that calls the log output function
% (funcName)s The function name that calls the log output function
%(lineno)d The line of code where the statement that calls the log output function is located
%(created)f The current time, in UNIX standard A floating point number representing time.
%(relativeCreated)d The number of milliseconds since the Logger was created when outputting log information.
%(asctime)s The current time in string form. The default format is "2003-07-08 16:49:45,896". What follows the comma is the thread ID in milliseconds
%(thread)d. There may be no
%(threadName)s thread names. There may be no
%(process)d process ID. There may not be messages output by
%(message)s users
Attached is a directly usable log template:
""" logging配置 """ import os import logging.config # 定义三种日志输出格式 开始 standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' \ '[%(levelname)s][%(message)s]' #其中name为getlogger指定的名字 simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s' id_simple_format = '[%(levelname)s][%(asctime)s] %(message)s' # 定义日志输出格式 结束 logfile_dir = os.path.dirname(os.path.abspath(__file__)) # log文件的目录 logfile_name = 'all2.log' # log文件名 # 如果不存在定义的日志目录就创建一个 if not os.path.isdir(logfile_dir): os.mkdir(logfile_dir) # log文件的全路径 logfile_path = os.path.join(logfile_dir, logfile_name) # log配置字典 LOGGING_DIC = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': standard_format }, 'simple': { 'format': simple_format }, }, 'filters': {}, 'handlers': { #打印到终端的日志 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', # 打印到屏幕 'formatter': 'simple' }, #打印到文件的日志,收集info及以上的日志 'default': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', # 保存到文件 'formatter': 'standard', 'filename': logfile_path, # 日志文件 'maxBytes': 1024*1024*5, # 日志大小 5M 'backupCount': 5, 'encoding': 'utf-8', # 日志文件的编码,再也不用担心中文log乱码了 }, }, 'loggers': { #logging.getLogger(__name__)拿到的logger配置 # 这里的logger对象名字为''是为了getLogger()获取不同的日志对象时能获取相同的配置,当想要让不同的日志对象有不同的配 # 置时,可在这里添加logger对象 # 当getLogger()获取的logger对象名称不存在时,如果存在key=''的配置,则使用默认key=''的配置 '': { 'handlers': ['default', 'console'], # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕 'level': 'DEBUG', 'propagate': True, # 向上(更高level的logger)传递 }, }, } def load_my_logging_cfg(event_log): logging.config.dictConfig(LOGGING_DIC) # 导入上面定义的logging配置 # logger = logging.getLogger(__name__) # 生成一个log实例 # logger.info(event_log) # 记录事件的日志
Test:
""" MyLogging Test """ import time import logging import my_logging # 导入自定义的logging配置 logger = logging.getLogger(__name__) # 生成logger实例 def demo(): logger.debug("start range... time:{}".format(time.time())) logger.info("中文测试开始。。。") for i in range(10): logger.debug("i:{}".format(i)) time.sleep(0.2) else: logger.debug("over range... time:{}".format(time.time())) logger.info("中文测试结束。。。") if __name__ == "__main__": my_logging.load_my_logging_cfg() # 在你程序文件的入口加载自定义logging配置 demo()
Related recommendations :
Use the logging module in Python instead of print (a concise guide to logging)
Usage examples of the logging module in Python
The above is the detailed content of What is the use of the logging module in python? Introduction to the usage of logging module. For more information, please follow other related articles on the PHP Chinese website!

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1
Powerful PHP integrated development environment