Recently, I was made a service which can provide a simple way to get best model. so, i spent lot of time to read source code of auto-sklearn, auto-sklearn is an automated machine learning toolkit and a drop-in replacement for a scikit-learn estimator.

when I write my logging module I found the logging module of auto-sklearn which used yaml file as config, the config file:

 ---
version: 1
disable_existing_loggers: False
formatters:
simple:
format: '[%(asctime)s: %(levelname)s] %(message)s' handlers:
console:
class: logging.StreamHandler
level: WARNING
formatter: simple
stream: ext://sys.stdout file_handler:
class: logging.FileHandler
level: DEBUG
formatter: simple
filename: autosklearn.log root:
level: ERROR
handlers: [console, file_handler] loggers:
server:
level: INFO
handlers: [file_handler]
propagate: no

the caller can define loggers、handlers、formatters here, after that, caller need write setup code and get logger code.

 # -*- encoding: utf-8 -*-
import logging
import logging.config
import os
import yaml def setup_logger(output_file=None, logging_config=None):
# logging_config must be a dictionary object specifying the configuration
if not os.path.exists(os.path.dirname(output_file)):
os.makedirs(os.path.dirname(output_file))
if logging_config is not None:
if output_file is not None:
logging_config['handlers']['file_handler']['filename'] = output_file
logging.config.dictConfig(logging_config)
else:
with open(os.path.join(os.path.dirname(__file__), 'logging.yaml'),
'r') as fh:
logging_config = yaml.safe_load(fh)
if output_file is not None:
logging_config['handlers']['file_handler']['filename'] = output_file
logging.config.dictConfig(logging_config) def _create_logger(name):
return logging.getLogger(name) def get_logger(name):
logger = PickableLoggerAdapter(name)
return logger class PickableLoggerAdapter(object): def __init__(self, name):
self.name = name
self.logger = _create_logger(name) def __getstate__(self):
"""
Method is called when pickle dumps an object. Returns
-------
Dictionary, representing the object state to be pickled. Ignores
the self.logger field and only returns the logger name.
"""
return {'name': self.name} def __setstate__(self, state):
"""
Method is called when pickle loads an object. Retrieves the name and
creates a logger. Parameters
----------
state - dictionary, containing the logger name. """
self.name = state['name']
self.logger = _create_logger(self.name) def debug(self, msg, *args, **kwargs):
self.logger.debug(msg, *args, **kwargs) def info(self, msg, *args, **kwargs):
self.logger.info(msg, *args, **kwargs) def warning(self, msg, *args, **kwargs):
self.logger.warning(msg, *args, **kwargs) def error(self, msg, *args, **kwargs):
self.logger.error(msg, *args, **kwargs) def exception(self, msg, *args, **kwargs):
self.logger.exception(msg, *args, **kwargs) def critical(self, msg, *args, **kwargs):
self.logger.critical(msg, *args, **kwargs) def log(self, level, msg, *args, **kwargs):
self.logger.log(level, msg, *args, **kwargs) def isEnabledFor(self, level):
return self.logger.isEnabledFor(level)

get_logger return a logger object, setup_logger setup logger handler which define output where.

when you use it,like this

 from .util import get_logger, setup_logger

 APP_DIR = os.path.dirname(os.path.abspath(__file__))
setup_logger(output_file=os.path.join(APP_DIR, 'logs', 'server.log'))
LOG = get_logger("server")

Define a global variable LOG for other modules to call.

all done.

python logging with yaml的更多相关文章

  1. Python logging 模块和使用经验

    记录下常用的一些东西,每次用总是查文档有点小麻烦. py2.7 日志应该是生产应用的重要生命线,谁都不应该掉以轻心 有益原则 级别分离 日志系统通常有下面几种级别,看情况是使用 FATAL - 导致程 ...

  2. (转)python logging模块

    python logging模块 原文:http://www.cnblogs.com/dahu-daqing/p/7040764.html 1 logging模块简介 logging模块是Python ...

  3. python logging模块可能会令人困惑的地方

    python logging模块主要是python提供的通用日志系统,使用的方法其实挺简单的,这块就不多介绍.下面主要会讲到在使用python logging模块的时候,涉及到多个python文件的调 ...

  4. python logging 配置

    python logging 配置 在python中,logging由logger,handler,filter,formater四个部分组成,logger是提供我们记录日志的方法:handler是让 ...

  5. Python LOGGING使用方法

    Python LOGGING使用方法 1. 简介 使用场景 场景 适合使用的方法 在终端输出程序或脚本的使用方法 print 报告一个事件的发生(例如状态的修改) logging.info()或log ...

  6. python logging 日志轮转文件不删除问题

    前言 最近在维护项目的python项目代码,项目使用了 python 的日志模块 logging, 设定了保存的日志数目, 不过没有生效,还要通过contab定时清理数据. 分析 项目使用了 logg ...

  7. python logging模块使用

    近来再弄一个小项目,已经到收尾阶段了.希望加入写log机制来增加程序出错后的判断分析.尝试使用了python logging模块. #-*- coding:utf-8 -*- import loggi ...

  8. python Logging的使用

    日志是用来记录程序在运行过程中发生的状况,在程序开发过程中添加日志模块能够帮助我们了解程序运行过程中发生了哪些事件,这些事件也有轻重之分. 根据事件的轻重可分为以下几个级别: DEBUG: 详细信息, ...

  9. Python logging日志系统

    写我小小的日志系统 配置logging有以下几种方式: 1)使用Python代码显式的创建loggers, handlers和formatters并分别调用它们的配置函数: 2)创建一个日志配置文件, ...

随机推荐

  1. git 创建分支并关联远程分支

    从master分支,重新拉取出一个新的分支,名字为dev,具体命令如下: 1. 切换到被copy的分支(master),从服务器拉取最新版本 $git checkout master $git pul ...

  2. YII报错笔记:<pre>PHP Notice &#039;yii\base\ErrorException&#039; with message &#039;Uninitialized string offset: 0&#039; in /my/test/project/iot/vendor/yiisoft/yii2/base/Model.php:778

    YII常见报错笔记 报错返回的代码如下: <pre>PHP Notice 'yii\base\ErrorException' with message 'Uninitialized str ...

  3. Ubuntu安装指定版本的docker

    系统环境: Ubuntu 16.0.4 安装版本: docker  17.03.2 在进现在这家公司初期,需要使用rancher部署一个k8s集群,由于rancher也是由docker启动的,加上k8 ...

  4. 120 Triangle 三角形最小路径和

    给出一个三角形(数据数组),找出从上往下的最小路径和.每一步只能移动到下一行中的相邻结点上.比如,给你如下三角形:[     [2],    [3,4],   [6,5,7],  [4,1,8,3]] ...

  5. 104 Maximum Depth of Binary Tree 二叉树的最大深度

    给定一个二叉树,找出其最大深度.二叉树的深度为根节点到最远叶节点的最长路径上的节点数.案例:给出二叉树 [3,9,20,null,null,15,7],    3   / \  9  20    /  ...

  6. slf4j介绍以及与Log4j、Log4j2、LogBack整合方法

    翻了一下百度和官网.这么介绍slf4j. slf4j 全称 Simple Logging Facade for Java,是日志框架的一种抽象,那么也就是说 slf4j 是不能单独使用的必须要有其他实 ...

  7. BZOJ3073: [Pa2011]Journeys(线段树优化建图 Dijkstra)

    题意 \(n\)个点的无向图,构造\(m\)次边,求\(p\)到任意点的最短路. 每次给出\(a, b, c, d\) 对于任意\((x_{a \leqslant x \leqslant b}, y_ ...

  8. awk累加

    {a+=substr($14,1,1)}END{a=(a=="")?0:a;print a}' 对a进行累加,如果最后a=0的话,结果为0,否则为a,最后输出a

  9. PHP 根据两点的经纬度计算距离

    /** * @name 根据经纬度确定两点的距离[地理位置] * @author tbj * @param float $lat 纬度值 * @param float $lng 经度值 * @date ...

  10. 使用 Azure 创建存储和检索文件

    本指南将以循序渐进的方式帮助您使用 Azure 将文件存储到云中.我们将逐一介绍如何创建存储账户.创建容器.上传文件.检索文件和删除文件.在本教程中完成的所有操作均符合 1 元试用条件. 本指南将以循 ...