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
相關文章
相關標籤/搜索