1 Star 0 Fork 15

logicjwell/python-dbhelper

forked from fangzheng/python-dbhelper 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
logger.py 3.01 KB
一键复制 编辑 原始数据 按行查看 历史
zfang 提交于 2019-04-02 18:32 . fix: 封装logger类
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
@version : v1.0
@author : fangzheng
@contact : zfang@hillinsight.com
@software : PyCharm
@filename : logger.py
@create time: 2019/3/26 22:49
@describe :
@use example: python logger.py [param1 param2]
-------------------------------------------------
"""
import logging
import os
import sys
class Logger():
def __init__(self, level="debug",
name=os.path.split(os.path.splitext(sys.argv[0])[0])[-1],
log_name=None,
log_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "log"),
use_console=True):
'''
set_level: 设置日志的打印级别,默认为DEBUG
name: 日志中将会打印的name,默认为运行程序的name
log_name: 日志文件的名字,默认为当前时间(年-月-日.log)
log_path: 日志文件夹的路径,默认为logger.py同级目录中的log文件夹
use_console: 是否在控制台打印,默认为True
'''
self.logger = logging.getLogger(name)
if level.lower() == "critical":
self.logger.setLevel(logging.CRITICAL)
elif level.lower() == "error":
self.logger.setLevel(logging.ERROR)
elif level.lower() == "warning":
self.logger.setLevel(logging.WARNING)
elif level.lower() == "info":
self.logger.setLevel(logging.INFO)
elif level.lower() == "debug":
self.logger.setLevel(logging.DEBUG)
else:
self.logger.setLevel(logging.NOTSET)
if not os.path.exists(log_path):
os.makedirs(log_path)
if log_name:
log_file_path = os.path.join(log_path, log_name)
log_handler = logging.FileHandler(log_file_path+".log")
log_handler.setFormatter(
logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s"))
self.logger.addHandler(log_handler)
if use_console:
console_handler = logging.StreamHandler()
console_handler.setFormatter(logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s"))
self.logger.addHandler(console_handler)
def addHandler(self, hdlr):
self.logger.addHandler(hdlr)
def removeHandler(self, hdlr):
self.logger.removeHandler(hdlr)
def critical(self, msg, *args, **kwargs):
self.logger.critical(msg, *args, **kwargs)
def warning(self, msg, *args, **kwargs):
self.logger.warning(msg, *args, **kwargs)
def error(self, msg, *args, **kwargs):
self.logger.error(msg, *args, **kwargs)
def info(self, msg, *args, **kwargs):
self.logger.info(msg, *args, **kwargs)
def debug(self, msg, *args, **kwargs):
self.logger.debug(msg, *args, **kwargs)
def log(self, level, msg, *args, **kwargs):
self.logger.log(level, msg, *args, **kwargs)
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/logicjwell/python-dbhelper.git
git@gitee.com:logicjwell/python-dbhelper.git
logicjwell
python-dbhelper
python-dbhelper
master

搜索帮助