logging的在脚本中的使用

2、logging在脚本中的使用

一 最简单的使用方法.

这只是最简单的使用方法,一般在比较大的脚本中不太适用python

配置以下:

import logging

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    filename='myapp.log',
                    filemode='a')

logger = logging.getLogger(__name__)

logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')

# result
# 2016-12-06 18:24:27,230 tt.py[line:16] DEBUG This is debug message
# 2016-12-06 18:24:27,230 tt.py[line:17] INFO This is info message
# 2016-12-06 18:24:27,230 tt.py[line:18] WARNING This is warning message

2、getlogger的使用

在本身编写的脚本和框架中,咱们须要共享配置.一般在脚本初始化的时候配置全局logging.而后在其余脚本中直接条用便可(相似django的使用方法)shell

# 写在初始化脚本中,一般在__init__.py

import logging
import logging.config
from os import path


def log_handler():
    p = path.join(path.dirname(__file__), "order.log")

    config = {
        "version": 1,
        "disable_existing_loggers": False,
        "root": {"handlers": ["default"], "level": "INFO", "propagate": False},
        "formatters": {
            "standard": {
                "format": "%(asctime)s [%(threadName)s:%(thread)d] [%(name)s:%(module)s:%(funcName)s:%(lineno)d ]"
                "[%(levelname)s]- %(message)s"
            }
        },
        "handlers": {
            "console": {
                "level": "INFO",
                "class": "logging.StreamHandler",
                "formatter": "standard",
            },
            "default": {
                "class": "logging.handlers.RotatingFileHandler",
                "level": "INFO",
                "formatter": "standard",
                "filename": p,
                "mode": "w+",
                "maxBytes": 1024 * 1024 * 5,  # 5 MB
                "backupCount": 20,
                "encoding": "utf8",
            },
        },
        "loggers": {
            "default": {
                "handlers": ["default", "console"],
                "level": "INFO",
                "propagate": False,
            }
        },
    }

    logging.config.dictConfig(config)


log_handler()

调用方法:

from make_order.utils import UtilMixin

logger = logging.getLogger("default")
logger.info("打印日志")

日志效果

# 格式化说明: 当前时间 线程 线程id logger名字 py文件 模块 行 日志等级 日志内容.
2019-01-10 15:41:50,664 [MainThread:4460946880] [default:deco:wrapper:12 ][INFO]- 当前运行函数名:bpm_audit 当前函数说明:个人审批-待审批
2019-01-10 15:41:50,664 [MainThread:4460946880] [default:bpm:bpm_audit:21 ][INFO]- 审批类型:PriceTeamApprove
2019-01-10 15:41:51,169 [MainThread:4460946880] [default:utils:send:37 ][INFO]- Request INFO:method:post
相关文章
相关标签/搜索