Python通过配置文件控制日志打印

news/2024/7/7 5:01:34 标签: python, Log, 日志, 滚动, handler

引言:

作为一个Java程序员,我们使用过log4j,logback等一系列的日志打印框架,还有比较简单的@Slf4j,只需要一个annotation,就可以很简单的输出日志了,并且日志文件可以按天或者按大小进行滚动,那么在Python里面该如何做呢?其实Java里面的日志配置可以非常平滑的迁移到Python里面来。

日志配置文件:

1、log.yaml

配置文件的格式有非常多的形式,比如.ini格式,.yaml格式,.json格式,.yaml比较好理解,我们就拿这个格式来举例,文件内容如下所示:

python">version: 1
formatters:
  simple:
    format: '%(asctime)s - %(funcName)s - %(lineno)d - %(levelname)s - %(message)s'

handlers:
  console:
    class: logging.StreamHandler
    level: DEBUG
    formatter: simple
  file:
    class: logging.handlers.TimedRotatingFileHandler
    filename: ./log/logging.log
    when: D
    interval: 1
    backupCount: 5
    level: DEBUG
    formatter: simple

loggers:
  bizLog:
    level: DEBUG
    handlers: [file]
    propagate: no
root:
  level: DEBUG
  handlers: [console]

2、formatters

首先定义一个formatter,它决定了日志输出的格式,有很多的预置变量,下表个大家列出来了,可以根据自己的需要进行增减:

Attribute name

Format

Description

args

You shouldn’t need to format this yourself.

The tuple of arguments merged into msg to produce message, or a dict whose values are used for the merge (when there is only one argument, and it is a dictionary).

asctime

%(asctime)s

Human-readable time when the LogRecord was created. By default this is of the form ‘2003-07-08 16:49:45,896’ (the numbers after the comma are millisecond portion of the time).

created

%(created)f

Time when the LogRecord was created (as returned by time.time()).

exc_info

You shouldn’t need to format this yourself.

Exception tuple (à la sys.exc_info) or, if no exception has occurred, None.

filename

%(filename)s

Filename portion of pathname.

funcName

%(funcName)s

Name of function containing the logging call.

levelname

%(levelname)s

Text logging level for the message ('DEBUG''INFO''WARNING''ERROR''CRITICAL').

levelno

%(levelno)s

Numeric logging level for the message (DEBUGINFOWARNINGERRORCRITICAL).

lineno

%(lineno)d

Source line number where the logging call was issued (if available).

message

%(message)s

The logged message, computed as msg % args. This is set when Formatter.format() is invoked.

module

%(module)s

Module (name portion of filename).

msecs

%(msecs)d

Millisecond portion of the time when the LogRecord was created.

msg

You shouldn’t need to format this yourself.

The format string passed in the original logging call. Merged with args to produce message, or an arbitrary object (see Using arbitrary objects as messages).

name

%(name)s

Name of the logger used to log the call.

pathname

%(pathname)s

Full pathname of the source file where the logging call was issued (if available).

process

%(process)d

Process ID (if available).

processName

%(processName)s

Process name (if available).

relativeCreated

%(relativeCreated)d

Time in milliseconds when the LogRecord was created, relative to the time the logging module was loaded.

stack_info

You shouldn’t need to format this yourself.

Stack frame information (where available) from the bottom of the stack in the current thread, up to and including the stack frame of the logging call which resulted in the creation of this record.

thread

%(thread)d

Thread ID (if available).

threadName

%(threadName)s

Thread name (if available).

参考链接:logging — Logging facility for Python — Python 3.7.17 documentation

3、handlers

我们接收到日志输出的消息以后,该如何打印这些日志,是打印到控制台,还是打印到文件里面,就在这个模块里面进行定义,上面例子里面定义了两个handler,一个是打印到控制台的handler,一个是按时间滚动打印到文件里handler,一般情况下用这两个handler就够了。

参考链接:logging.handlers — Logging handlers — Python 3.7.17 documentation

4、loggers

最后我们需要定义的就是logger,它是我们在业务代码里面需要根据名称获取的logger,业务代码通过logger来打印具体的日志

测试代码

python">import logging.config
import yaml

with open('log.yaml', 'r') as f:
    config = yaml.safe_load(f.read())
    logging.config.dictConfig(config)

logger = logging.getLogger("bizLog")

logger.error('error message')

如果我们使用.yaml格式的配置文件,我们需要引入yaml包,然后进行配置。从测试代码里面我们看到我们根据配置的logger 名称获取到logger,然后就可以进行打印了。

注意事项:

1、filename: ./log/logging.log:需要我们手动创建/log目录,否则会报错


http://www.niftyadmin.cn/n/5326491.html

相关文章

若依微服务中的上传文件的前后端实现

前端&#xff1a; &#xff1a;limit用来控制上传文件数量的默认一 <template><div class"app-container"><el-form :model"queryParams" ref"queryForm" size"small" :inline"true" v-show"showSearc…

一、docker的安装与踩坑

目录 一、安装docker&#xff08;centos7安装docker&#xff09;1.安装环境前期准备2.参考官网安装前准备3.参考官网安装步骤开始安装docker4.运行首个容器 二、安装一些软件的踩坑1.启动docker踩坑2.安装mysql踩坑3.罕见问题 三、关于我的虚拟机 一、安装docker&#xff08;ce…

【html】Video元素的属性介绍和用法

简言 HTML <video> 元素 用于在 HTML 或者 XHTML 文档中嵌入媒体播放器&#xff0c;用于支持文档内的视频播放。 平常若涉及到视频内容&#xff0c;就会使用到它。 video Video使用 只有一个视频源 只有一个视频的话&#xff0c;在\video元素中的src属性填入即可。 …

【AI】无人零售和边缘计算

目录 一、什么是边缘计算 1.1 边缘计算的定义 1.2 边缘计算的作用 1.3 边缘计算的关键技术 1.4 边缘计算的应用场景 二、边缘计算在无人零售中的应用 一、什么是边缘计算 1.1 边缘计算的定义 边缘计算&#xff08;Edge Computing&#xff09;是一种分布式计算范式&#…

开源内容管理系统Wagtail本地安装运行并结合内网穿透实现公网访问

文章目录 前言1. 安装并运行Wagtail1.1 创建并激活虚拟环境 2. 安装cpolar内网穿透工具3. 实现Wagtail公网访问4. 固定的Wagtail公网地址 前言 Wagtail是一个用Python编写的开源CMS&#xff0c;建立在Django Web框架上。Wagtail 是一个基于 Django 的开源内容管理系统&#xf…

如何用pthon连接mysql和mongodb数据库【极简版】

文章目录 发现宝藏前言1. 连接mysql1.1 安装 PyMySQL1.2 导入 PyMySQL1.3 建立连接1.4 创建游标对象1.5 执行查询1.6 关闭连接1.7 完整示例 2. 连接mongodb2.1 安装 PyMongo2.2 导入 PyMongo2.3 建立连接2.4 选择数据库和集合2.5 插入文档2.6 查询文档2.7 更新文档2.8 删除文档…

购物网站更新版

本文使用创作助手。 下面是一个使用Python编写的简单购物网站框架&#xff0c;包含了登录和注册功能&#xff0c;并且可以将注册信息保存到文本文档中&#xff0c;并且可以将登录信息与文本文档中的信息进行比对。 from flask import Flask, render_template, request, redir…

pyx文件编译为pyd/so文件(分别在windows/linux系统下)

Python有以下几种类型的文件&#xff1a; py&#xff1a;Python控制台程序的源代码文件pyx&#xff1a;是Python语言的一个编译扩展&#xff0c;它实际上是Cython语言的源代码文件&#xff08;可以理解为既支持Python语言也支持C/C&#xff09;。pyc&#xff1a;Python字节码文…