一.第三方模块coloredlogs

# Create a logger object.
import logging
logger = logging.getLogger('your-module') # Initialize coloredlogs.
import coloredlogs
coloredlogs.install(level='DEBUG') # Some examples.
logger.debug("this is a debugging message")
logger.info("this is an informational message")
logger.warn("this is a warning message")
logger.error("this is an error message")
logger.critical("this is a critical message")

二.代码实现

示例一

#!/usr/bin/env python
# -*- coding: utf- -*- class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m' def disable(self):
self.HEADER = ''
self.OKBLUE = ''
self.OKGREEN = ''
self.WARNING = ''
self.FAIL = ''
self.ENDC = '' print bcolors.WARNING + "Warning: No active frommets remain. Continue?"
print bcolors.OKBLUE + "Warning: No active frommets remain. Continue?"
print bcolors.OKGREEN + "Warning: No active frommets remain. Continue?"
print bcolors.HEADER + "Warning: No active frommets remain. Continue?"
print bcolors.FAIL + "Warning: No active frommets remain. Continue?"
print bcolors.ENDC + "Warning: No active frommets remain. Continue?" 

示例二

import logging

BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)

#The background is set with 40 plus the number of the color, and the foreground with 30

#These are the sequences need to get colored ouput
RESET_SEQ = "\033[0m"
COLOR_SEQ = "\033[1;%dm"
BOLD_SEQ = "\033[1m" def formatter_message(message, use_color = True):
if use_color:
message = message.replace("$RESET", RESET_SEQ).replace("$BOLD", BOLD_SEQ)
else:
message = message.replace("$RESET", "").replace("$BOLD", "")
return message COLORS = {
'WARNING': YELLOW,
'INFO': WHITE,
'DEBUG': BLUE,
'CRITICAL': YELLOW,
'ERROR': RED
} class ColoredFormatter(logging.Formatter):
def __init__(self, msg, use_color = True):
logging.Formatter.__init__(self, msg)
self.use_color = use_color def format(self, record):
levelname = record.levelname
if self.use_color and levelname in COLORS:
levelname_color = COLOR_SEQ % (30 + COLORS[levelname]) + levelname + RESET_SEQ
record.levelname = levelname_color
return logging.Formatter.format(self, record) # Custom logger class with multiple destinations
class ColoredLogger(logging.Logger):
FORMAT = "[$BOLD%(name)-20s$RESET][%(levelname)-18s] %(message)s ($BOLD%(filename)s$RESET:%(lineno)d)"
COLOR_FORMAT = formatter_message(FORMAT, True)
def __init__(self, name):
logging.Logger.__init__(self, name, logging.DEBUG)
color_formatter = ColoredFormatter(self.COLOR_FORMAT)
console = logging.StreamHandler()
console.setFormatter(color_formatter) self.addHandler(console)
return # logging.setLoggerClass(ColoredLogger)
color_log = logging.getLogger(__name__)
color_log.setLevel(logging.DEBUG) color_log.debug("test")
color_log.info("test")
color_log.warning("test")
color_log.error("test")
color_log.critical("test")

Windows下python环境

转自:https://www.oschina.net/code/snippet_614988_26500

#! /usr/bin/env python
# coding: utf-8
import logging,os
import ctypes FOREGROUND_WHITE = 0x0007
FOREGROUND_BLUE = 0x01 # text color contains blue.
FOREGROUND_GREEN= 0x02 # text color contains green.
FOREGROUND_RED = 0x04 # text color contains red.
FOREGROUND_YELLOW = FOREGROUND_RED | FOREGROUND_GREEN STD_OUTPUT_HANDLE= -11
std_out_handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
def set_color(color, handle=std_out_handle):
bool = ctypes.windll.kernel32.SetConsoleTextAttribute(handle, color)
return bool class Logger:
def __init__(self, path,clevel = logging.DEBUG,Flevel = logging.DEBUG):
self.logger = logging.getLogger(path)
self.logger.setLevel(logging.DEBUG)
fmt = logging.Formatter('[%(asctime)s] [%(levelname)s] %(message)s', '%Y-%m-%d %H:%M:%S')
#设置CMD日志
sh = logging.StreamHandler()
sh.setFormatter(fmt)
sh.setLevel(clevel)
#设置文件日志
fh = logging.FileHandler(path)
fh.setFormatter(fmt)
fh.setLevel(Flevel)
self.logger.addHandler(sh)
self.logger.addHandler(fh) def debug(self,message):
self.logger.debug(message) def info(self,message):
self.logger.info(message) def war(self,message,color=FOREGROUND_YELLOW):
set_color(color)
self.logger.warn(message)
set_color(FOREGROUND_WHITE) def error(self,message,color=FOREGROUND_RED):
set_color(color)
self.logger.error(message)
set_color(FOREGROUND_WHITE) def cri(self,message):
self.logger.critical(message) if __name__ =='__main__':
logyyx = Logger('yyx.log',logging.WARNING,logging.DEBUG)
logyyx.debug('一个debug信息')
logyyx.info('一个info信息')
logyyx.war('一个warning信息')
logyyx.error('一个error信息')
logyyx.cri('一个致命critical信息')

python输出有色记录的更多相关文章

  1. python 输出颜色的与样式的方法

    上次遇到这个问题就想写下来,其实当时我也不怎么会,老师说这个东西不需要理解,只需要死记硬背,写的多了就记住了,所以今天搜集了几篇文章,加上自己的理解,写下了这篇python 输出颜色的样式与方法的文章 ...

  2. python 输出颜色与样式的方法

    上次遇到这个问题就想写下来,其实当时我也不怎么会,老师说这个东西不需要理解,只需要死记硬背,写的多了就记住了,所以今天搜集了几篇文章,加上自己的理解,写下了这篇python 输出颜色的样式与方法的文章 ...

  3. python输出颜色与样式的方法

    一.输出颜色与样式的方法 上次遇到这个问题就想写下来,其实当时我也不怎么会,老师说这个东西不需要理解,只需要死记硬背,写的多了就记住了,所以今天搜集了几篇文章,加上自己的理解,写下了这篇python ...

  4. Python 输出文件内容到网络端口

    Python 输出文件内容到网络端口 $ cat mySocketTest.py import sys import time import socket if __name__ == "_ ...

  5. python输出缓冲区的问题

    碰到的问题,一段代码,print在前,log的在后,查看日志中log的反而在前面.是python输出缓冲区的问题. python输出缓冲区要满 4k 才写入文件,除非禁用缓存或者强制输出或者程序结束. ...

  6. python3.4学习笔记(二十六) Python 输出json到文件,让json.dumps输出中文 实例代码

    python3.4学习笔记(二十六) Python 输出json到文件,让json.dumps输出中文 实例代码 python的json.dumps方法默认会输出成这种格式"\u535a\u ...

  7. Python爬虫个人记录(三)爬取妹子图

    这此教程可能会比较简洁,具体细节可参考我的第一篇教程: Python爬虫个人记录(一)豆瓣250 Python爬虫个人记录(二)fishc爬虫 一.目的分析 获取煎蛋妹子图并下载 http://jan ...

  8. Python爬虫个人记录(二) 获取fishc 课件下载链接

    参考: Python爬虫个人记录(一)豆瓣250 (2017.9.6更新,通过cookie模拟登陆方法,已成功实现下载文件功能!!) 一.目的分析 获取http://bbs.fishc.com/for ...

  9. Python 输出百分比的两种方式

    Python 输出百分比的两种方式 注: 在python3环境下测试. 方式1:直接使用参数格式化:{:.2%} {:.2%}: 显示小数点后2位 显示小数点后2位: >>> pri ...

随机推荐

  1. Prime Path[POJ3126] [SPFA/BFS]

    描述 孤单的zydsg又一次孤单的度过了520,不过下一次不会再这样了.zydsg要做些改变,他想去和素数小姐姐约会. 所有的路口都被标号为了一个4位素数,zydsg现在的位置和素数小姐姐的家也是这样 ...

  2. 什么是OKR?

    什么是OKR OKR全称是Objectives and Key Results,即目标与关键成果法.OKR是一套定义和跟踪目标及其完成情况的管理工具和方法.1999年 Intel公司发明了这种方法,后 ...

  3. Spring MVC4 + Spring Security4 + Hibernate实例

    http://www.yiibai.com/spring-security/spring-mvc-4-and-spring-security-4-integration-example.html 在这 ...

  4. 100405之python程序安装

    Python的安装 注意安装的path和.exe可执行文件的命名方式 例如py2或者py3 sublime的安装 一.Sublime Text 3安装(64位Windows操作系统): 1.双击 Su ...

  5. C_狐狸和兔子的故事

    题目描述 围绕着山顶有10个洞,一只狐狸和一只兔子各住一个洞.狐狸总想吃掉兔子.一天兔子对狐狸说:“你想吃我有一个条件,先把洞从1-10编上号,你从10号洞出发,先到1号洞找我:第二次隔1个洞找我,第 ...

  6. ASCII到Unicode到UTF-8

    1.很久以前使用的是ASCII:只有一个字节,也就是2的8次方,可以表示256个不同状态,电脑最初起源于美国,够用了,刚开始只是使用了127位,后来后面的部分被他们用来表示一些横线字符之类的128-2 ...

  7. H5C303

    H5C303 1.CSS3 一些js功能可以通过css3实现. 坚持渐进增强原则. 另一侧:优雅降级hack 3.选择器 1)属性选择器:根据指定名称的属性来查找元素 E是元素 li[style]{ ...

  8. Mac 10.12下安装python3环境

    python3感觉用虚拟环境会比较好操作一些,也不用直接卸载python2. 一.基于brew快速安装 # 安装python3 brew install python3 # 安装pip(好像3自带pi ...

  9. 未能加载文件或程序集“SuperMap.Data.dll”

    重新配置的新的开发环境,使用的是原来的工程文件,编译通过,运行报错:"未能加载文件或程序集"SuperMap.Data.dll"或它的某一个依赖项.找不到指定的模块&qu ...

  10. Foxmail中配置O365邮箱和Hotmail邮箱

    一.简述 平时我们经常使用第三方的邮箱工具来管理邮箱.可能性能比Outlook好很多,比如Foxmail,而且也能和Skype会议关联的很好.本文就讲如何在Outlook中关联Office365邮箱和 ...