python日志输出
# !/usr/bin/python
# -*- coding: utf-8 -*-
"""
@contact: 微信 1257309054
@file: 日志输出.py
@time: 2021/5/19 18:09
@author: LDC
"""
import logging
import os
import datetime
def make_log(msg, level='debug'):
'''
:param msg: 内容
:param level: 日志级别,debug,info,error
:return:
'''
# 打印日志
# 创建日志文件夹
if os.path.exists('./log') == False:
os.mkdir("./log")
SERVER_LOG_PATH = './log/{}.log'.format(datetime.datetime.now().strftime('%Y-%m-%d'))
# 定义一个logging的对象,命名为mylog
LOGGER = logging.getLogger('machine_data')
# 设置级别为WARNING
LOGGER.setLevel(logging.DEBUG if level == 'debug' else logging.INFO)
if not LOGGER.handlers:
# 创建一个handler,用于写入日志文件
fh = logging.FileHandler(SERVER_LOG_PATH, encoding='utf-8')
else:
fh = LOGGER.handlers[0]
fh.setLevel(logging.DEBUG if level == 'debug' else logging.INFO)
# 定义handler的输出格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
fh.setFormatter(formatter)
# 给Logger添加handler
LOGGER.addHandler(fh)
# 在控制台显示
LOGGER.propagate = True
LOGGER.__getattribute__(level)(msg)
fh.close()
if __name__ == '__main__':
make_log('hello world')
公众号
关注我,我们一起成长~~