Python logging practice

Ten hair 2021-01-20 20:44:17
python logging practice


Log for the development of system development 、 Debugging and running the whole process plays a very important role , During the debugging phase, you need to look at the log to find out what the problem is , In the runtime, if the program crashes , Log can record the cause of program crash . And sometimes python The role of the script is to return text to the caller , At this point, we need to distinguish the return value from the log used for debugging trace . This paper introduces python Common usage .

logging Two ways of log configuration are provided , Simple journal (logging.basicConfig And standard streaming framework

Simple journal

logging.basicConfig Configuration log , Standard output and files are generally supported ( Cannot be configured at the same time )

# -*- coding:utf-8 -*-
import logging
import sys
# Log output to file tenmao.log, Level is INFO, Configure log format and date time format at the same time
#logging.basicConfig(level=logging.INFO,
# format='%(asctime)s %(filename)s %(levelname)s %(message)s',
# datefmt='%a %d %b %Y %H:%M:%S',
# filename='tenmao.log',
# filemode='a')
# Log output to standard error sys.stderr( The default is standard output sys.stdout),filename and stream They are mutually exclusive. , It can't be configured at the same time
logging.basicConfig(level=logging.DEBUG, stream=sys.stderr,
format='%(asctime)s %(filename)s[line:%(lineno)d]%(levelname)s %(message)s')
logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')
logging.error('This is error message')
logging.critical('This is critical message')
  • Output log content : tenmao.log
Sat 16 Jan 2021 22:45:28 simple_log.py INFO This is info message
Sat 16 Jan 2021 22:45:28 simple_log.py WARNING This is warning message
Sat 16 Jan 2021 22:45:28 simple_log.py ERROR This is error message
Sat 16 Jan 2021 22:45:28 simple_log.py CRITICAL This is critical message

Standard configuration : Streaming

logging Modules include Logger,Handler,Filter,Formatter Four parts .

  • Logger Recorder , Used to set log collection .
  • Handler processor , Send the log record to the appropriate path .
  • Filter filter , Provides better granularity control , It can decide which logging to output .
  • Formatter formatter , Indicates the format of the log in the final output .
  • Configure sample code
# -*- coding:utf-8 -*-
import logging
# First step , Create a logger
# 1, Create a logger logger
logger = logging.getLogger()
# 2, Set the log level of the logger , The log level here is the lowest level that a logger can record , It's different from the back Handler in setLevel Log level of
logger.setLevel(logging.DEBUG)
# The second step , Create a log processor Handler. Create a Handler, Used to write logs to a file
# 3, Create a Handler, For writing log files , The path of the log file is self-defined
logFile = './log.txt'
fh = logging.FileHandler(logFile, mode='a', encoding='utf-8')
# 4, Set the log level saved to the file
fh.setLevel(logging.INFO)
# The third step , Definition Handler The output format of
# 5, The log output format is defined as follows
format= logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s')
# 6, Set up Write to the log file Handler The log format of
fh.setFormatter(format)
# Step four , take Handler Add to the logger logger in
logger.addHandler(fh)
# alike , Create a Handler For console output logs
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
ch.setFormatter(format)
logger.addHandler(ch)
# Output log
logger.info("This is info message")
logger.warning("This is warning message")
logger.error("This is error message")
logger.critical("This is critical message")

example

  • Abnormal information
try:
raise Exception("hello error")
except Exception as e:
logger.error(" Login error , The reason is :{}".format(e))
logger.error(" Login error ,stack trace", exc_info=True)
else:
logger.info(" Landing successful ...")

exc_info=True You can output the exception stack

The output is as follows

2021-01-16 23:01:42,203 mylog.py[line:35] INFO This is info message
2021-01-16 23:01:42,203 mylog.py[line:36] WARNING This is warning message
2021-01-16 23:01:42,204 mylog.py[line:37] ERROR This is error message
2021-01-16 23:01:42,204 mylog.py[line:38] CRITICAL This is critical message
2021-01-16 23:01:42,204 mylog.py[line:43] ERROR Login error , The reason is :hello error
2021-01-16 23:01:42,204 mylog.py[line:44] ERROR Login error ,stack trace
Traceback (most recent call last):
File "mylog.py", line 41, in <module>
raise Exception("hello error")
Exception: hello error

Reference resources

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

版权声明
本文为[Ten hair]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/01/20210120203803662f.html

  1. A series of problems and solutions in Java calling Python
  2. python自动化爬取淘宝商品数据导入execl表格
  3. Using Python to automatically punch in the pin / enterprise wechat
  4. 【分享】python+requests接口测试基础
  5. Python automatically crawls Taobao product data and imports it into excel table
  6. C++/Python描述 628. 三个数的最大乘积
  7. Python的容器有哪些?分别有什么作用?
  8. python+requests接口测试基础
  9. 20 行代码:Serverless 架构下用 Python 轻松搞定图像分类和预测
  10. python+requests接口测试基础
  11. [share] Python + requests interface test foundation
  12. C + + / Python description 628. Maximum product of three numbers
  13. What are Python containers and what are their functions?
  14. Testing foundation of Python + requests interface
  15. 20 lines of code: easy to do image classification and prediction with Python under serverless architecture
  16. Python爬取优质高清壁纸网站:彼岸
  17. Testing foundation of Python + requests interface
  18. 【人生苦短,我学 Python】基础篇——列表(Day8)
  19. Python crawls high quality HD Wallpaper website: the other side
  20. Python图像增强与特效-利用百度AI进行黑白图像上色
  21. 【七天搞定Python】day01.Python环境配置、pip、IDE、注释、变量,数据类型、标识符/关键字、输出、输入
  22. Life is short, I learn Python
  23. Python image enhancement and special effects - using Baidu AI to color black and white images
  24. Python environment configuration, Pip, IDE, comment, variable, data type, identifier / keyword, output, input
  25. 为什么说Python是最伟大的语言?看图就知道了 - 知乎
  26. Why is Python the greatest language? Just look at the picture. - Zhihu
  27. 通过创建视频游戏来学习 Python
  28. Learn Python by creating video games
  29. Python3版本下创建计算给定日期范围内工作日方法
  30. Creating a method to calculate working days within a given date range in Python 3
  31. 图解爬虫,用几个最简单的例子带你入门Python爬虫
  32. Graphical crawler, with a few of the simplest examples to take you to the introduction of Python crawler
  33. python+requests基础知识
  34. Basic knowledge of Python + requests
  35. python自定义windowsr日志支持文件分割
  36. python+requests基础知识
  37. Python custom Windowsr log supports file segmentation
  38. Basic knowledge of Python + requests
  39. 高级测试 | Python笔试题
  40. 火了!开源的 Python 抢票神器,过年回家就看这一波了!
  41. Python 爬虫进阶 - 前后端分离有什么了不起,过程超详细!
  42. 【python】使用pip提示ModuleNotFoundError
  43. 【python】虚拟环境搭建
  44. Advanced test | Python written test questions
  45. Fire! Open source Python ticket grabbing artifact, come home to see this wave of New Year!
  46. Python crawler advanced - before and after the end of the separation of what great, super detailed process!
  47. [Python] prompt modulenotfounderror with PIP
  48. Building a virtual environment
  49. Serverless 架构下用 Python 轻松搞定图像分类和预测
  50. Easy image classification and prediction with Python under serverless architecture
  51. python协程爬取某网站的老赖数据
  52. Python coroutine crawls Laolai data of a website
  53. 使用Python分析姿态估计数据集COCO的教程
  54. Using Python to analyze the data set coco of attitude estimation
  55. win环境 python3 flask 上手整理 环境搭建(一)
  56. Getting started with win environment python3 flash
  57. Python实现一个论文下载器,赶紧收藏
  58. win环境 python3 flask 上手整理 快速上手-基础操作(二)
  59. Python 中常见的配置文件写法
  60. Python to achieve a paper Downloader, quickly collect