import logging
import os
from logging.handlers import TimedRotatingFileHandler
import coloredlogs

# 设置颜色
coloredlogs.DEFAULT_FIELD_STYLES = {'asctime': {'color': 'green'}, 'hostname': {'color': 'magenta'},
'levelname': {'color': 'green', 'bold': True}, 'request_id': {'color': 'yellow'},
'name': {'color': 'blue'}, 'programname': {'color': 'cyan'},
'threadName': {'color': 'yellow'}} class Log:
__instances = {} @classmethod
def getLogger(cls, name=os.path.abspath(__name__)):
if name not in cls.__instances:
       # 日志文件夹路径
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
log_dir = 'logs'
if not log_dir.startswith('/'):
         # 日志文件夹
log_dir = os.path.join(BASE_DIR, log_dir)
       # 递归生成
if not os.path.isdir(log_dir):
os.makedirs(log_dir, mode=0o755) log_file = os.path.join(log_dir, "app.log")
logger = logging.getLogger(name)
       # 设置日志格式
fmt = '%(asctime)s [%(levelname)s] [%(name)s] %(filename)s[line:%(lineno)d] [%(threadName)s] %(message)s'
formater = logging.Formatter(fmt) ch = logging.StreamHandler()
ch.setLevel(Log.__getLogLevel())
ch.setFormatter(formater)
logger.addHandler(ch) coloredlogs.install(fmt=fmt, level=Log.__getLogLevel(), logger=logger) fh = TimedRotatingFileHandler(log_file, when='M', interval=1, backupCount=7, encoding='utf-8')
fh.setLevel(Log.__getLogLevel())
fh.setFormatter(formater)
logger.setLevel(Log.__getLogLevel())
logger.addHandler(fh)
cls.__instances[name] = logger
return cls.__instances[name] @staticmethod # 设置日志等级
def __getLogLevel():
return logging.INFO if __name__ == '__main__':
Log.getLogger().error('log测试数据')
Log.getLogger().info('log测试数据')
Log.getLogger().warning('log测试数据')
Log.getLogger().debug('log测试数据')

  

Python通过logging记录日志并应用coloredlogs在控制台输出有色字体的更多相关文章

  1. Python logging记录日志

    Python logging记录日志 调试的几种方法: 使用print()在控制台上输出 使用assert断言 使用logging模块 logging提供了一组便利的函数,用来做简单的日志,(当然也能 ...

  2. python logging记录日志的方式

    python的logging模块提供了标准的日志接口,可以通过它存储各种格式的日志,日志级别等级:critical > error > warning > info > deb ...

  3. Python之logging模块

    一.引言 之前在写一些小程序的时候想把日志内容打到文件中,所以就自己写了一个logger.py的程序,如下: #!/usr/bin/python # -*- coding=utf-8 -*- impo ...

  4. python的logging模块之读取yaml配置文件。

    python的logging模块是用来记录应用程序的日志的.关于logging模块的介绍,我这里不赘述,请参见其他资料.这里主要讲讲如何来读取yaml配置文件进行定制化的日志输出. python要读取 ...

  5. Python:logging 的巧妙设计

    引言 logging 的基本用法网上很多,这里就不介绍了.在引入正文之前,先来看一个需求: 假设需要将某功能封装成类库供他人使用,如何处理类库中的日志? 数年前在一个 C# 开发的项目中,我用了这样的 ...

  6. python中logging模块的用法

    很多程序都有记录日志的需求,并且日志中包含的信息即有正常的程序访问日志,还可能有错误.警告等信息输出,python的logging模块提供了标准的日志接口,你可以通过它存储各种格式的日志,loggin ...

  7. python中logging模块

    1. 日志的等级 DEBUG.INFO.NOTICE.WARNING.ERROR.CRITICAL.ALERT.EMERGENCY 级别 何时使用 DEBUG 详细信息,典型地调试问题时会感兴趣. 详 ...

  8. Python模块——logging模块

    logging模块简介 logging模块定义的函数和类为应用程序和库的开发实现了一个灵活的事件日志系统.logging模块是Python的一个标准库模块, 由标准库模块提供日志记录API的关键好处是 ...

  9. python 运行日志logging代替方案

    以下是自己写的 记录日志的代码.(和logging不搭嘎,如果如要学loggging模块,本文末尾有他人的链接.) # prtlog.py ############################## ...

随机推荐

  1. laravel中一些非常常用的php artisan命令

    php artisan 命令在开发laravel项目中非常常用,下面是一些总结 composer config -g repo.packagist composer https://mirrors.a ...

  2. python3检测ossfs可用性+钉钉通知

    #!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019-12-02 15:16 # @Author : Anthony # @Emai ...

  3. TZOJ5255: C++实验:三角形面积

    #include<iostream> #include<iomanip> #include<math.h> #include<cmath> using ...

  4. Java多线程编程之读写锁【ReentrantReadWriteLock】

    有时候我们需要有这样的需求:        对于同一个文件进行读和写操作,普通的锁是互斥的,这样读的时候会加锁,只能单线程的读,我们希望多线程的进行读操作,并且读的时候不能进行写操作,写的时候不能进行 ...

  5. C#特性的学习(一)

    1.预定定义特性之一:AttributeUsage AttributeUsage有三个属性: 第一个属性:ValidOn 规定特性可被放置的语言元素,默认是AttributeTargets.All.

  6. Git命令和使用

    Git & GitHub Git是一个工具,用于命令行操作 GitHub是一个协同工作平台 包括: Remote original Repository - 远程主仓库(上线唯一仓库) Rem ...

  7. semaphore demo 并行 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    import 'dart:async'; import 'package:semaphore/semaphore.dart'; import 'dart:io'; import 'dart:conve ...

  8. golang实现路由中间件middleware

    registerHandlers.go package router import ( "../ctrl" "../funcs" "github.co ...

  9. fastjson源码分析之序列化

    fastJson是很常用的序列化工具,用了这么久一直想底层看一下它的设计,探究一下它序列化和反序列化效率高的秘密.现在从最基础的用法开始,一点点揭开fastJson神秘的面纱.(版本:1.2.50) ...

  10. saleae逻辑分析仪-串口

    安装软件 下载:https://www.saleae.com 连线 逻辑分析仪CHx分别连接UART的rx和tx 配置Logic 选择串口 设置波特率 还可以自定义显示方式 打开串口助手 波特率和Lo ...