2022年 11月 6日

Python中写日志方式

在python开发的时候,有些时候我们需要将日志信息存储下来用以程序的排查。那么就需要定义一个写日志的函数。而且这个函数最好能够满足在控制台打印出来的同时,将信息存储到本地文件中。
该方法有以下功能:

  1. 会在该文件logo.py的父级目录下新建一个log的文件夹,日志文件都会存放在新建的log文件夹下。
  2. 日志信息会在控制台打印出来,与使用print效果一样。
  3. 在控制台打印出来的同时,日志信息也会写入到本地日志文件logfile里。
# -*- coding:utf-8 -*-
import sys
import os
import logging

CurrentFile = os.path.abspath(__file__)
CurrentPath = os.path.dirname(CurrentFile)
FatherPath = os.path.dirname(CurrentPath)
def create_logo(pid, name, logofile):
    # 定义一个文件,用来存储日志信息
    if not os.path.exists(os.path.join(FatherPath, 'log')):
        os.makedirs(os.path.join(FatherPath, 'log'))
    logofile = os.path.join(FatherPath, 'log', logofile)
    # 创建一个logger,以进程名定义
    logger = logging.getLogger("pid:%d name:%s" % (pid, name))
    logger.setLevel(logging.DEBUG)
    # 创建一个handler,用于写入日志文件
    fh = logging.FileHandler(logofile, encoding='utf-8')
    fh.setLevel(logging.DEBUG)
    # 再创建一个handler,用于输出到控制台
    ch = logging.StreamHandler(sys.stdout) 
    # ch = logging.StreamHandler(sys.stderr)# stderr是以错误输出,打印出来的是红色
    ch.setLevel(logging.DEBUG)
    # 定义handler的输出格式
    formatter = logging.Formatter('%(asctime)s  %(name)s  %(module)s  %(levelname)s: %(message)s',
                                  datefmt='[%Y/%m/%d %H:%M:%S]')
    fh.setFormatter(formatter)
    # ch.setFormatter(formatter) # 是否打印handler的format
    # 给logger添加handler
    logger.addHandler(fh) # 用于写入日志
    logger.addHandler(ch) # 用于输出到控制台
    return logger

if __name__ == '__main__':
    import time
    today = time.strftime('%Y%m%d',time.localtime(time.time()))
    logger = create_logo(os.getpid(),__name__,F'{today}.log')
    logger.info('xxxx')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38