python中logging日志基本用法,和進程安全問題


低配版

import logging

logging.debug('debug message')    # 調試模式
logging.info('info message')    # 正常運轉模式
logging.warning('warning message')  # 警告模式
logging.error('error message')      # 錯誤模式
logging.critical('critical message')    # 致命的 崩潰模式

while 1:
    try:
        num = input('>>>')
        num = int(num)

    except ValueError:
        logging.warning('輸入非數字警告')

標准版

import logging
# 1.產生logger對象
logger = logging.getLogger()

# 2 產生其他對象(屏幕對象,文件對象)
sh = logging.StreamHandler()
fh1 = logging.FileHandler('staff.log', encoding='utf-8')
fh2 = logging.FileHandler('boss.log', encoding='utf-8')

# 3,設置顯示格式
formater = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
formater1 = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
formater2 = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# 4,給對象綁定格式
sh.setFormatter(formater)
fh1.setFormatter(formater1)
fh2.setFormatter(formater2)

# 5 給logger對象綁定其他對象
logger.addHandler(sh)
logger.addHandler(fh1)
logger.addHandler(fh2)

# 6 設置顯示級別
# 其他對象的級別要高於logger的級別
logger.setLevel(10)
sh.setLevel(20)
fh1.setLevel(20)
fh2.setLevel(30)


logging.debug('debug message')    # 調試模式
logging.info('info message')    # 正常運轉模式
logging.warning('warning message')  # 警告模式
logging.error('error message')      # 錯誤模式
logging.critical('crit

高配版

import os
import logging.config

# 定義三種日志輸出格式 開始

# 標准版 格式
standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' \
                  '[%(levelname)s][%(message)s]' #其中name為getlogger指定的名字
# 簡單版 格式
simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'

# boss版格式(lowb版)
id_simple_format = '[%(levelname)s][%(asctime)s] %(message)s'

# 定義日志輸出格式 結束

file_path = os.path.dirname(__file__)

logfile_name = file_path + '\staff.log'  # log文件名

# log配置字典

LOGGING_DIC = {
    'version': 1,  # 版本
    'disable_existing_loggers': False,  # 可否重復使用之前的logger對象
    'formatters': {
        'standard': {
            'format': standard_format
        },
        'simple': {
            'format': simple_format
        },
        'boss_formatter': {
            'format': id_simple_format
        },
    },
    'filters': {},
    'handlers': {
        #打印到終端的日志
        'stream': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',  # 打印到屏幕
            'formatter': 'simple'
        },
        #打印到文件的日志,收集info及以上的日志  文件句柄
        'file': {
            'level': 20,
            'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件
            'formatter': 'standard',  # 標准
            'filename': logfile_name,  # 日志文件
            'maxBytes': 300,  # 日志大小 300 bit
            'backupCount': 5,  #輪轉文件數
            'encoding': 'utf-8',  # 日志文件的編碼,再也不用擔心中文log亂碼了
        },
    },
    'loggers': {
        # logging.getLogger(__name__)拿到的logger配置
        '': {
            'handlers': ['stream', 'file'],  # 這里把上面定義的兩個handler都加上,即log數據既寫入文件又打印到屏幕
            'level': 'DEBUG',  # 總級別
            'propagate': True,  # 向上(更高level的logger)傳遞
        },
    },
}
# 字典中第一層的所有key都是固定不可變的。

logging.config.dictConfig(LOGGING_DIC)
logger = logging.getLogger()  # 這個logger對象是通過自己個性化配置的logger對象
logger.info('運轉正常')



# def load_my_logging_cfg():
#     logging.config.dictConfig(LOGGING_DIC)  # 導入上面定義的logging配置
#     logger = logging.getLogger(__name__)  # 生成一個log實例
#     logger.info('It works!')  # 記錄該文件的運行狀態
####    settings.LOGGING_DIC['handlers']['file']['filename'] = 路徑地址   # 通過操作字典 可實現動態設置log文件的存儲路徑,和文件名
# if __name__ == '__main__':
#     load_my_logging_cfg()

 

關於logging模塊的進程安全問題

logging 是線程安全的,也就是說,在一個進程內的多個線程同時往同一個文件寫日志是安全的。

但是多個進程往同一個文件寫日志不是安全的。

https://www.cnblogs.com/restran/p/4743840.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM