day6_logging模块

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/7/11 9:12
# @Author  : 大坏男孩
# @File    : day6_logging模块.py
# @Software: PyCharm
# @license : Copyright(C), 未来集团有限公司
# @Contact : 110@163.com

"""
logging:日志模块
日志文件的级别(从低到高):debug、info、warning、error、critical
PS:低级别的日志信息,不能写入高级别的日志文件
levelname = 日志信息级别
filename = 产生日志信息的文件名
lineno = 产生日志的代码行号
message = 日志的内容
asctime = 日志产生的时间
"""
import logging

logging.basicConfig(
    # 配置日志文件的级别  -->级别要大写
    level=logging.DEBUG,
    # 配置日志输出到哪个文件,默认"a"模式:追加
    filename="log_test",
    # 配置日志输出到文件的模式  可"a"或者"a+"
    filemode="a+",
    # format 配置日志输出内容
    format="%(levelname)s %(filename)s %(asctime)s %(lineno)s %(message)s"
)

logging.debug("顾城--门前")
logging.info("草在结它的种子")
logging.warning("风在摇它的叶子")
logging.error("我们站着,不说话")
logging.critical("就十分美好")

  

# 用函数的写法
"""
1、logger = logging.getLogger() -->拿到日志的写权限
2、logger.setLevel("INFO")  -->配置日志文件的级别
3、ch = logging.FileHandler("filename","a+",encoding="utf8") -->配置日志输出到哪个文件
4、fm = logging.Formatter("%(levelname)s %(filename)s %(asctime)s %(lineno)s %(message)s")
5、th = logging.StreamHandler()  -->输出日志内容到控制台(屏幕)
6、th.setFormatter(fm)   -->通过setFormatter()把fm给到th,th往控制台输出时,就按照fm的格式输出
7、ch.setFormatter(fm)   -->通过setFormatter()把fm给到ch,ch往日志文件输出时,就按照fm的格式输出
8、logger.addHandler(ch)  logger得到ch的功能, 能够往文件输出日志
9、logger.addHandler(th)  logger得到th的功能, 能够往屏幕输出日志
"""
import logging
def logs():
    # 拿到日志的写权限
    logger = logging.getLogger()
    # 配置日志文件的级别
    logger.setLevel("DEBUG")
    # 配置日志输出到哪个文件
    ch = logging.FileHandler("C:\UsersAdministratorPycharmProjectsliyebinpython基础python模块详解log_test",encoding="gbk")
    # 配置输出内容
    fm = logging.Formatter("%(levelname)s %(filename)s %(asctime)s %(lineno)s %(message)s")
    # 输出日志内容到控制台(屏幕)
    th = logging.StreamHandler()
    # 通过setFormatter把 fm 给到 th  th往控制台输出时,就按照fm的格式输出
    th.setFormatter(fm)
    # 通过setFormatter把 fm 给到 ch  ch往日志文件输出时,就按照fm的格式输出
    ch.setFormatter(fm)
    # logger得到ch的功能,能够往文件输出日志
    logger.addHandler(ch)
    # logger得到th的功能,能够往屏幕输出日志
    logger.addHandler(th)
    return logger
if __name__ == '__main__':    # https://www.cnblogs.com/kex1n/p/5975575.html
    l = logs()
    l.info("有内鬼,终止交易!!!")

  

一行代码一行诗
原文地址:https://www.cnblogs.com/huainanhai/p/11172695.html