Python日志模块logging简介

时间:2022-08-30 15:57:48

日志处理是项目的必备功能,配置合理的日志,可以帮助我们了解系统的运行状况、定位位置,辅助数据分析技术,还可以挖掘出一些额外的系统信息。

本文介绍Python内置的日志处理模块logging的常见用法。

1,日志等级

日志是分等级的,这点不难理解,任何信息都有轻重缓急之分,通过分级,我们可以方便的对日志进行刷选过滤,提高分析效率。

简单说,日志有以下等级:

DEBUG,INFO,WARNING,ERROR,CRITICAL

其重要性依次增强。一般的,这五个等级就足够我们日常使用了。

2,日志格式

日志本质上记录某一事件的发生,那么它应当包括但不限于以下信息:

事件等级,发生时间,地点(代码位置),错误信息

Python日志模块logging简介

3,logging模块的四大组件

Python日志模块logging简介

通过这四大组件,我们便可以*配置自己的日志格式。

4,案例展示

在实际应用中,一般会按照时间或者预置的大小对日志进行定期备份和分割,我们下面就按照这两点分别进行介绍:

4-1,按照预置的文件大小配置日志,并自动分割备份

代码:

 #!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import logging.handlers
import os def get_logger():
log_path = "./logs" if not os.path.isdir(log_path):
os.mkdir(log_path)
os.chmod(log_path, 0777) all_log = log_path + os.path.sep + "all.log"
error_log = log_path + os.path.sep + "error.log" if not os.path.isfile(all_log):
os.mknod(all_log)
os.chmod(all_log, 0777) if not os.path.isfile(error_log):
os.mknod(error_log)
os.chmod(error_log, 0777) log_format = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s") # get logger object
my_logger = logging.getLogger("my_logger")
my_logger.setLevel(logging.DEBUG) # auto split log file by interval specified(every minute), record debug message and above.
rf_handler = logging.handlers.TimedRotatingFileHandler(all_log, when='M', interval=1, backupCount=3)
rf_handler.setLevel(logging.DEBUG)
rf_handler.setFormatter(log_format) # don't split log file, only record error message and above.
f_handler = logging.FileHandler(error_log)
f_handler.setLevel(logging.ERROR)
f_handler.setFormatter(log_format) my_logger.addHandler(rf_handler)
my_logger.addHandler(f_handler) return my_logger def test():
msg = {"debug": "This is a debug log",
"info": "This is a info log",
"warning": "This is a warning log",
"error": "This is a error log",
"critical": "This is a critical log"} for k, v in msg.items():
if k == "debug":
logger.debug(v)
elif k == "info":
logger.info(v)
elif k == "warning":
logger.warning(v)
elif k == "error":
logger.error(v)
elif k == "critical":
logger.critical(v) if __name__ == '__main__':
index = 1
logger = get_logger() while True:
test()
print(index)
index = index + 1

实际效果:

Python日志模块logging简介

all.log保存最新的日志,历史副本按照时间后缀进行保存,最多留存三个。

4-2,按照预置的文件大小配置日志,并自动分割备份

代码:

 #!/usr/bin/env python
# -*- coding: utf-8 -*- import logging
from logging.handlers import RotatingFileHandler import os def test():
msg = {"debug": "This is a debug log",
"info": "This is a info log",
"warning": "This is a warning log",
"error": "This is a error log",
"critical": "This is a critical log"} for k, v in msg.items():
if k == "debug":
logger.debug(v)
elif k == "info":
logger.info(v)
elif k == "warning":
logger.warning(v)
elif k == "error":
logger.error(v)
elif k == "critical":
logger.critical(v) def get_logger():
dir_path = "./logs"
file_name = "rotating_log"
if not os.path.isdir(dir_path):
os.mkdir(dir_path)
os.chmod(dir_path, 0777) file_path = dir_path + "/" + file_name
if not os.path.isfile(file_path):
os.mknod(file_path)
os.chmod(file_path, 0777) my_logger = logging.getLogger("rotating_log")
my_logger.setLevel(level=logging.INFO) # auto split log file at max size of 4MB
r_handler = RotatingFileHandler(file_path, maxBytes=4*1024*1024, backupCount=3)
r_handler.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
r_handler.setFormatter(formatter) my_logger.addHandler(r_handler) return my_logger if __name__ == '__main__':
logger = get_logger()
index = 1
while True:
test()
print(index)
index = index + 1

最终效果:

Python日志模块logging简介

Python日志模块logging简介的更多相关文章

  1. python日志模块logging

    python日志模块logging   1. 基础用法 python提供了一个标准的日志接口,就是logging模块.日志级别有DEBUG.INFO.WARNING.ERROR.CRITICAL五种( ...

  2. 【python】【logging】python日志模块logging常用功能

    logging模块:应用程序的灵活事件日志系统,可以打印并自定义日志内容 logging.getLogger 创建一个log对象 >>> log1=logging.getLogger ...

  3. Python 日志模块logging

    logging模块: logging是一个日志记录模块,可以记录我们日常的操作. logging日志文件写入默认是gbk编码格式的,所以在查看时需要使用gbk的解码方式打开. logging日志等级: ...

  4. Python日志模块logging用法

    1.日志级别 日志一共分成5个等级,从低到高分别是:DEBUG INFO WARNING ERROR CRITICAL. DEBUG:详细的信息,通常只出现在诊断问题上 INFO:确认一切按预期运行 ...

  5. python日志模块logging学习

    介绍 Python本身带有logging模块,其默认支持直接输出到控制台(屏幕),或者通过配置输出到文件中.同时支持TCP.HTTP.GET/POST.SMTP.Socket等协议,将日志信息发送到网 ...

  6. Python 日志模块 logging通过配置文件方式使用

    vim logger_config.ini[loggers]keys=root,infoLogger,errorlogger [logger_root]level=DEBUGhandlers=info ...

  7. Python日志模块logging&JSON

    日志模块的用法 json部分 先开一段测试代码:注意  str可以直接处理字典   eval可以直接将字符串转成字典的形式 dic={'key1':'value1','key2':'value2'} ...

  8. python日志模块---logging

    1.将日志打印到屏幕 import logging logging.debug('This is debug message---by liu-ke') logging.info('This is i ...

  9. Python—日志模块(logging)和网络模块

    https://blog.csdn.net/HeatDeath/article/details/80548310 https://blog.csdn.net/chosen0ne/article/det ...

随机推荐

  1. linux运维自动化shell脚本小工具

    linux运维shell 脚本小工具,如要分享此文章,请注明文章出处,以下脚本仅供参考,若放置在服务器上出错,后果请自负 1.检测cpu剩余百分比 #!/bin/bash #Inspect CPU # ...

  2. Javascript的delete

    Javascript中的激活对象(Activation object)和变量对象(Variable object):每个执行上下文在其内部都有一个Variable Object.与执行上下文类似,Va ...

  3. 【JavaScript回顾】继承

    组合继承 组合继承(combination inheritance),有时候也叫做伪经典继承,指的是将原型链和借用构造函数的 技术组合到一块,从而发挥二者之长的一种继承模式.其背后的思路是使用原型链实 ...

  4. Rabbit MQ安装配置及常见问题

    Window安装 1:RabbitMQ安装 1.1:安装Erlang:http://www.erlang.org/ 1.2:安装RabbitMQ:http://www.rabbitmq.com/dow ...

  5. Unity monodev环境搭建

    断点调试功能可谓是程序员必备的功能了.Unity3D支持编写js和c#脚本,但很多人可能不知道,其实Unity3D也能对程序进行断点调试的.不过这个断点调试功能只限于使用Unity3D自带的MonoD ...

  6. fragment中listview触发事件setOnItemClickListener不好使

    <listView/>中// listview点击 ,高度wrap_content改成fill_prarent

  7. sass、less、stylus的安装及使用

    一.什么是CSS预处器 CSS预处理器定义了一种新的语言,其基本思想是,用一种专门的编程语言,为CSS增加了一些编程的特性,将CSS作为目标生成文件,然后开发者就 只要使用这种语言进行编码工作.通俗的 ...

  8. day037 行记录的操作

    1.库操作 2.表操作 3.行操作 1.库操作 1)创建数据库 语法: create database 数据库名 charset utf8; 数据库命名规则: 由数字,字母,下划线,@,#,$ 等组成 ...

  9. leetcode541

    public class Solution { public string ReverseStr(string s, int k) { var len = s.Length; //记录k的倍数 //分 ...

  10. thinkphp和ueditor自定义后台处理方法整合

    先了解一下ueditor后台请求参数与返回参数格式规范: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 ...