最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python?import?logging日志(日志封裝)詳解

 更新時間:2026年01月17日 09:12:36   作者:墨痕訴清風(fēng)  
文章介紹了如何使用Python的logging模塊創(chuàng)建和配置日志類,包括初始化logger對象、設(shè)置日志級別和格式、自動分割日志文件等,還展示了如何在多個文件中使用日志功能,并通過配置文件進(jìn)行日志配置

創(chuàng)建日志類并使用

如何使用python自帶的 logging 模塊實(shí)現(xiàn)日志功能

初始化一個logger對象

1)引入模塊

import os
import logging
import sys

2)初始化變量,聲明logger對象

LOG_PATH = 'logs'   #設(shè)置log路徑
LOG_FILE = 'text.txt'    #設(shè)置log文件名

#設(shè)置根路徑為起始位置
logger = logging.getLogger(__name__)

3) 生成路徑

#生成log指定路徑

if os.path.exists(LOG_PATH):
    pass
else:
    os.mkdir(LOG_PATH)

4)指定logger輸出格式

    formatter = logging.Formatter('%(asctime)s %(levelname)-8s: %(message)s')
    
    file_handler = logging.FileHandler("%s/%s" % (LOG_PATH, LOG_FILE))
    
    # 可以通過setFormatter指定輸出格式
    file_handler.setFormatter(formatter)
    
    logger.addHandler(file_handler)

5)指定日志文件的輸出級別

分為如下幾個級別:

_nameToLevel = {
    'CRITICAL': CRITICAL,
    'FATAL': FATAL,
    'ERROR': ERROR,
    'WARN': WARNING,
    'WARNING': WARNING,
    'INFO': INFO,
    'DEBUG': DEBUG,
    'NOTSET': NOTSET,
} 

使用setLevel函數(shù)指定輸出級別 指定之后將只顯示級別以上的日志類型

logger.setLevel(logging.DEBUG)

6) 自動分割日志文件

python 提供了兩個處理器,方便我們分割文件:

  • logging.handlers.RotatingFileHandler -> 按照大小自動分割日志文件,一旦達(dá)到指定的大小重新生成文件
  • logging.handlers.TimedRotatingFileHandler -> 按照時間自動分割日志文件

TimedRotatingFileHandler(filename='logs/info/' +
                          info_file_name,
                          when='MIDNIGHT',
                          interval=1,
                          backupCount=7,
                          encoding='utf-8')
# filename:日志文件名
# when:日志文件按什么維度切分。'S'-秒;'M'-分鐘;'H'-小時;'D'-天;'W'-周
#       這里需要注意,如果選擇 D-天,那么這個不是嚴(yán)格意義上的'天',而是從你
#       項(xiàng)目啟動開始,過了24小時,才會從新創(chuàng)建一個新的日志文件,
#       如果項(xiàng)目重啟,這個時間就會重置。所以這里選擇'MIDNIGHT'-是指過了午夜
#       12點(diǎn),就會創(chuàng)建新的日志。
# interval:是指等待多少個單位 when 的時間后,Logger會自動重建文件。
# backupCount:是保留日志個數(shù)。默認(rèn)的0是不會自動刪除掉日志。

when是一個字符串用于描述滾動周期的基本單位,字符串的值及意義如下:

  • 'S': Seconds
  • 'M': Minutes
  • 'H': Hours
  • 'D': Days
  • 'W': Week day (0=Monday)
  • 'midnight': Roll over at midnight
  • interval: 滾動周期,單位有when指定,比如:when='D',interval=1,表示每天產(chǎn)生一個日志文件;
  • backupCount: 表示日志文件的保留個數(shù)

輸入日志內(nèi)容

#輸出debug類型日志
logger.debug("debug")

#多參數(shù)傳遞  輸入info類型日志
pam= "dshck"
pam2="cxjkdhc"
logger.info("%s%s"%(pam,pam2))

log.py 代碼如下

import os
import logging
from logging.handlers import TimedRotatingFileHandler
import datetime
import json

LOG_PATH = "log"
LOG_INFO = '_info.log'
LOG_ERROR = '_error.log'


class logger:
    def __init__(self,prefix_name = "flask"):
        if os.path.exists(LOG_PATH):
            pass
        else:
            os.mkdir(LOG_PATH)
        self.prefix = prefix_name
        self.info_logger = logging.getLogger("info")
        self.error_logger = logging.getLogger("error")
        self.format = logging.Formatter('[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s]\
[%(filename)s:%(lineno)d]' '[%(levelname)s] : %(message)s')
        #指定文件位置文件名以及輸出格式
        info_file_handler = logging.FileHandler("%s/%s%s" % (LOG_PATH, prefix_name,LOG_INFO))
        info_file_handler.setFormatter(self.format)
        error_file_handler = logging.FileHandler("%s/%s%s" % (LOG_PATH, prefix_name,LOG_ERROR))
        error_file_handler.setFormatter(self.format)
        self.info_logger.addHandler(info_file_handler)
        self.error_logger.addHandler(error_file_handler)
        # 指定日志的最低輸出級別
        self.info_logger.setLevel(logging.NOTSET)
        self.error_logger.setLevel(logging.ERROR)

    def debug(self, msg, *args, **kwargs):
        self.info_logger.debug(msg, *args, **kwargs)

    def info(self, msg, *args, **kwargs):
        self.info_logger.info(msg, *args, **kwargs)

    def warn(self, msg, *args, **kwargs):
        self.info_logger.warning(msg, *args, **kwargs)

    def warning(self, msg, *args, **kwargs):
        self.info_logger.warning(msg, *args, **kwargs)

    def error(self, msg, *args, **kwargs):
        self.error_logger.error(msg, *args, **kwargs)

    def fatal(self, msg, *args, **kwargs):
        self.error_logger.fatal(msg, *args, **kwargs)

    def critical(self, msg, *args, **kwargs):
        self.error_logger.critical(msg, *args, **kwargs)


# log =logger()
# log.info("jdshskh")
# log.error("hdskck")
# log.debug("1122debug")
# log.warn("warn")
# log.warning("warning")
# log.critical("critical")
# log.fatal("fatal")

log =logger("celery")
log.info("jdshskh")
log.error("hdskck")
log.debug("1122debug")
log.warn("warn")
log.warning("warning")
log.critical("critical")
log.fatal("fatal")

開源日志實(shí)例

import logging


logger = logging.getLogger()


def setup_logging(logfile, verbose):
    """
    設(shè)置日志記錄到日志文件/控制臺。
    :param logfile:要寫入日志的文件的路徑。
    :param verbose:如果為true,則啟用詳細(xì)日志記錄。
    """
    root_logger = logging.getLogger()

    default_formatter = logging.Formatter('%(asctime)-15s (%(name)s) %(filename)s[line:%(lineno)d] : %(message)s')

    if verbose:
        loglevel = logging.DEBUG
    else:
        loglevel = logging.INFO
    root_logger.setLevel(loglevel)

    console_log = logging.StreamHandler()
    console_log.setLevel(loglevel)
    console_log.setFormatter(default_formatter)
    root_logger.addHandler(console_log)

    if logfile in ('/dev/log', '/dev/syslog', '/var/run/syslog', '/var/run/log'):
        file_log = logging.handlers.SysLogHandler(address=logfile, facility='local1')
        syslog_formatter = logging.Formatter('beeswarm[%(process)d]: %(message)s')
        file_log.setFormatter(syslog_formatter)
    else:
        file_log = logging.FileHandler(logfile)
        file_log.setFormatter(default_formatter)
    file_log.setLevel(loglevel)
    root_logger.addHandler(file_log)

    # 日志按天自動創(chuàng)建
    """
    time_rotating_file_handler = handlers.TimedRotatingFileHandler(filename=logfile, when='S')
    #time_rotating_file_handler.setLevel(logging.ERROR)
    time_rotating_file_handler.setLevel(logging.INFO)
    time_rotating_file_handler.setFormatter(default_formatter)
    root_logger.addHandler(time_rotating_file_handler)
    """


if __name__ == '__main__':
    setup_logging(args.logfile, args.verbose)

    logger.info('Initializing BeeSwarm version {0}'.format(beeswarm.version))
    logger.debug('workdir = {0}, config = {1}, customize = {2}, clear_db = {3}, reset_password = {4}, max_sessions = {5}, start_webui = {6}.'.format(args.workdir,
config, args.customize, args.clearsessions, args.resetpw, args.max_sessions, not args.no_webui))
    logger.debug('workdir = {0}'.format())
    logger.error(...)
    logger.warning(...)

多日志輸出實(shí)例

配置文件log_config.py

# -*- coding: utf-8 -*-
import os
import time
import logging.config

cur_path = os.path.dirname(os.path.realpath(__file__))  # log_path是存放日志的路徑
log_path = os.path.join(os.path.dirname(cur_path), 'logs')
if not os.path.exists(log_path):
    os.mkdir(log_path)  # 如果不存在這個logs文件夾,就自動創(chuàng)建一個


def setp_log():
    LOGGING_CONFIG = {
        'version': 1,
        'disable_existing_loggers': False,
        'formatters': {
            # 日志格式
            'simple': {
                'format': '[%(asctime)s] [%(levelname)s] [%(pathname)s -- %(funcName)s:%(lineno)s] [%(message)s]'},
            # 簡單格式
            'standard': {
                #'format': '[%(asctime)s] [%(levelname)s] [%(pathname)s -- %(funcName)s:%(lineno)s] [%(message)s]'
                'format': '[%(asctime)s] [%(filename)s:%(lineno)s] [%(message)s]'
            },
        },
        # 定義具體處理日志的方式
        'handlers': {
            # 控制臺輸出
            'console_handler': {
                'level': 'DEBUG',
                'class': 'logging.StreamHandler',
                'formatter': 'simple'
            },
            # 默認(rèn)記錄所有日志,按日期滾動輸出到文件
            'info_handler': {
                'level': 'INFO',
                'class': 'logging.handlers.RotatingFileHandler',
                'filename': os.path.join(log_path, 'all-{}.log'.format(time.strftime('%Y-%m-%d'))),  # 按日分類
                'maxBytes': 1024 * 1024 * 5,  # 文件大小
                'backupCount': 5,  # 備份數(shù)
                'formatter': 'standard',  # 輸出格式
                'encoding': 'utf-8',  # 設(shè)置默認(rèn)編碼,否則打印出來漢字亂碼
            },
            # 輸出錯誤日志
            'error_handler': {
                'level': 'ERROR',
                'class': 'logging.handlers.RotatingFileHandler',
                'filename': os.path.join(log_path, 'error-{}.log'.format(time.strftime('%Y-%m'))),  # 按月分類
                'maxBytes': 1024 * 1024 * 5,  # 文件大小
                'backupCount': 5,  # 備份數(shù)
                'formatter': 'standard',  # 輸出格式
                'encoding': 'utf-8',  # 設(shè)置默認(rèn)編碼
            },

        },
        'loggers': {
            'log': {
                'handlers': ['console_handler', 'info_handler', 'error_handler'],
                'level': 'INFO',
                'propagate': True
            },
        }
    }
    logging.config.dictConfig(LOGGING_CONFIG)

測試代碼

aaa.py(加載)

# -*- coding: utf-8 -*-

from log_config import setp_log
setp_log()


import logging
logger = logging.getLogger('log')

logger.info("asdasd")
logger.error("asd")

bbb.py(調(diào)用)

import logging
logger = logging.getLogger('log')

logger.info("asdasd")
logger.critical("asd123")
logger.error("asd")

總結(jié)

以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Python爬蟲實(shí)現(xiàn)自動登錄、簽到功能的代碼

    Python爬蟲實(shí)現(xiàn)自動登錄、簽到功能的代碼

    這篇文章主要介紹了Python爬蟲實(shí)現(xiàn)自動登錄、簽到功能的代碼,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-08-08
  • pytorch實(shí)現(xiàn)Tensor變量之間的轉(zhuǎn)換

    pytorch實(shí)現(xiàn)Tensor變量之間的轉(zhuǎn)換

    今天小編就為大家分享一篇pytorch實(shí)現(xiàn)Tensor變量之間的轉(zhuǎn)換,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-02-02
  • PyQt5結(jié)合QtDesigner實(shí)現(xiàn)文本框讀寫操作

    PyQt5結(jié)合QtDesigner實(shí)現(xiàn)文本框讀寫操作

    本文將結(jié)合實(shí)例代碼,介紹PyQt5結(jié)合QtDesigner實(shí)現(xiàn)文本框讀寫操作,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-06-06
  • Python 3.6打包成EXE可執(zhí)行程序的實(shí)現(xiàn)

    Python 3.6打包成EXE可執(zhí)行程序的實(shí)現(xiàn)

    這篇文章主要介紹了Python 3.6打包成EXE可執(zhí)行程序的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-10-10
  • Python實(shí)現(xiàn)多種場景下查找并高亮Word文檔中的文本

    Python實(shí)現(xiàn)多種場景下查找并高亮Word文檔中的文本

    在處理長篇 Word 文檔時,快速定位關(guān)鍵信息并將其突出顯示是一項(xiàng)非常實(shí)用的技能,本文將深入探討如何使用 Python 實(shí)現(xiàn)多種場景下的 Word 文檔文本查找與高亮功能,有需要的小伙伴可以了解下
    2026-03-03
  • Python 通過xpath屬性爬取豆瓣熱映的電影信息

    Python 通過xpath屬性爬取豆瓣熱映的電影信息

    我喜歡看電影,可以說大部分熱門電影我都看過。處理愛好的目的,我看了看豆瓣熱映的電影列表。于是我寫了這個爬蟲把豆瓣熱映的電影都爬了下來。對頁面的處理主要是需要點(diǎn)擊顯示全部電影,然后爬取影片屬性,最后輸出文本。采用的還是scrapy框架。順便聊聊我的實(shí)現(xiàn)過程吧
    2021-11-11
  • Python中的元類編程入門指引

    Python中的元類編程入門指引

    這篇文章主要介紹了Python中的元類編程入門指引,來自于IBM官方網(wǎng)站技術(shù)文檔,需要的朋友可以參考下
    2015-04-04
  • 詳解如何使用Python?LXML庫來解析和處理XML文檔

    詳解如何使用Python?LXML庫來解析和處理XML文檔

    在數(shù)據(jù)處理過程中,XML(可擴(kuò)展標(biāo)記語言)常常被用作數(shù)據(jù)存儲和傳輸,Python的lxml庫是一個強(qiáng)大的庫,用于解析XML和HTML文檔,本文將向您介紹如何使用lxml庫來解析和處理XML文檔,需要的朋友可以參考下
    2023-08-08
  • Python中面向?qū)ο竽銘?yīng)該知道的一下知識

    Python中面向?qū)ο竽銘?yīng)該知道的一下知識

    這篇文章主要介紹了Python中面向?qū)ο竽銘?yīng)該知道的一下知識,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-07-07
  • Python OpenCV簡單的繪圖函數(shù)使用教程

    Python OpenCV簡單的繪圖函數(shù)使用教程

    本文主要為大家介紹了OpenCV中一些簡單的繪圖函數(shù)的使用教程,文中的示例代碼講解詳細(xì),對我們了解OpenCV有一定的幫助,感興趣的可以學(xué)習(xí)一下
    2022-01-01

最新評論

电白县| 阿荣旗| 收藏| 桐梓县| 揭阳市| 长葛市| 绵竹市| 都昌县| 甘孜县| 丰宁| 克山县| 恩平市| 阳原县| 庄浪县| 紫云| 博客| 博罗县| 防城港市| 墨玉县| 兴安盟| 诸城市| 吴江市| 常熟市| 海安县| 游戏| 砚山县| 濮阳市| 罗平县| 新民市| 辰溪县| 天津市| 凉山| 灵石县| 贵港市| 称多县| 虞城县| 横山县| 清水河县| 彭泽县| 吉首市| 奉贤区|