溫馨提示×

CentOS中Python日志配置與管理

小樊
44
2025-07-14 23:35:04
欄目: 編程語言

在CentOS系統中配置和管理Python日志通常涉及以下步驟:

1. 安裝Python和pip

確保你的CentOS系統上已經安裝了Python和pip(Python的包管理器)。如果沒有安裝,可以使用以下命令進行安裝:

sudo yum install python3 python3-pip

2. 創建Python腳本

創建一個Python腳本文件,例如 app.py,并在其中配置日志記錄。以下是一個基本的日志配置示例:

import logging

# 配置日志記錄
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    filename='app.log',  # 日志文件名
    filemode='a'  # 追加模式
)

# 獲取日志記錄器
logger = logging.getLogger(__name__)

# 記錄不同級別的日志
logger.debug('This is a debug message')
logger.info('This is an info message')
logger.warning('This is a warning message')
logger.error('This is an error message')
logger.critical('This is a critical message')

3. 運行Python腳本

在終端中運行你的Python腳本:

python3 app.py

4. 查看日志文件

運行腳本后,你會在當前目錄下看到一個名為 app.log 的日志文件。你可以使用以下命令查看日志文件內容:

cat app.log

5. 配置日志輪轉

為了防止日志文件過大,可以使用 logging.handlers.RotatingFileHandler 來配置日志輪轉。修改 app.py 中的日志配置部分:

from logging.handlers import RotatingFileHandler

# 配置日志記錄
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    filename='app.log',
    filemode='a',
    handlers=[
        RotatingFileHandler('app.log', maxBytes=10*1024*1024, backupCount=5),
        logging.StreamHandler()
    ]
)

6. 配置系統級日志

如果你希望將Python日志發送到系統級日志(例如syslog),可以使用 logging.handlers.SysLogHandler。修改 app.py 中的日志配置部分:

from logging.handlers import SysLogHandler

# 配置日志記錄
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        SysLogHandler(address='/dev/log'),
        logging.StreamHandler()
    ]
)

7. 使用配置文件管理日志

為了更方便地管理日志配置,可以使用配置文件。Python的 logging 模塊支持使用配置文件進行配置。常見的配置文件格式有INI和JSON。

使用INI配置文件

創建一個名為 logging.conf 的文件,內容如下:

[loggers]
keys=root,my_logger

[handlers]
keys=fileHandler,consoleHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=fileHandler,consoleHandler

[logger_my_logger]
level=DEBUG
handlers=fileHandler,consoleHandler
qualname=my_logger
propagate=0

[handler_fileHandler]
class=FileHandler
level=DEBUG
formatter=simpleFormatter
args=('my_app.log', 'a')

[handler_consoleHandler]
class=StreamHandler
level=INFO
formatter=simpleFormatter
args=(sys.stdout,)

[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=%Y-%m-%d %H:%M:%S

然后在Python腳本中加載配置文件:

import logging
import logging.config

# 加載配置文件
logging.config.fileConfig('logging.conf')

# 獲取日志記錄器
logger = logging.getLogger('my_logger')

# 記錄日志
logger.debug('This is a debug message')
logger.info('This is an info message')
logger.warning('This is a warning message')
logger.error('This is an error message')
logger.critical('This is a critical message')

使用JSON配置文件

創建一個名為 logging.json 的文件,內容如下:

{
    "version": 1,
    "formatters": {
        "simple": {
            "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
        }
    },
    "handlers": {
        "file": {
            "class": "logging.FileHandler",
            "level": "DEBUG",
            "formatter": "simple",
            "filename": "my_app.log",
            "mode": "a"
        },
        "console": {
            "class": "logging.StreamHandler",
            "level": "INFO",
            "formatter": "simple",
            "stream": "ext://sys.stdout"
        }
    },
    "loggers": {
        "my_logger": {
            "handlers": ["file", "console"],
            "level": "DEBUG",
            "propagate": false
        }
    }
}

然后在Python腳本中加載配置文件:

import logging
import json
import logging.config

# 加載配置文件
with open('logging.json', 'rt') as f:
    config = json.load(f)
logging.config.dictConfig(config)

# 獲取日志記錄器
logger = logging.getLogger('my_logger')

# 記錄日志
logger.debug('This is a debug message')
logger.info('This is an info message')
logger.warning('This is a warning message')
logger.error('This is an error message')
logger.critical('This is a critical message')

通過以上步驟,你可以在CentOS系統上配置和管理Python日志。根據你的需求,可以選擇不同的日志處理程序和格式化程序來滿足你的日志管理需求。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女