[root@node-1 library]# cat dolog.py
#!/bin/env python
ANSIBLE_METADATA = { 'metadata_version': 'alpha',
'status': ['preview'],
'supported_by': 'lin.wang',
'release_date': '2018-05-09'}
DEOCUMENTATION = """
---
module: dolog
version_added: "1.0"
short_descriptions: logging with log level
description:
- write the logs for doctor ,use "delegate_to: localhost" ,will write log at local logfile.
opetions:
level:
- [debug,info,warn,error,critical]
host: "task inventory_hostname"
message: "message info"
path: logfile path|default("{{ logfile }}")
delegate_to: localhost
cause log file be created at localhost
"""
EXAMPLES = """
# Example from Ansible Playbooks
dolog:
message: "xxxxxxxxx."
path: "{{ logfile }}"
host: "{{ hostname }}"
format: "{{ LOGFMT }}"
delegate_to: localhost
"""
import os
import time
import logging
from ansible.module_utils.basic import AnsibleModule
date = time.strftime("%Y-%m-%d",time.localtime())
DIS_LEVEL = "INFO"
def path_logfile(path=None):
"""
default the log path is /tmp/escloud-2018-*
"""
if not path:
filename = 'escloud-%s.log'%date
path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
path = '%s%s%s'%(path,os.sep,filename)
if not os.path.exists(path):
os.popen('touch %s'%path)
return path def get_logger(logpath=None):
ret = logging.getLogger()
fh = logging.FileHandler(logpath)
fm = logging.Formatter("%(asctime)s %(levelname)s %(message)s")
fh.setFormatter(fm)
ret.addHandler(fh)
return ret def main():
module = AnsibleModule(
argument_spec = dict(
message = dict(required=True, type='str'),
level = dict(choice=['debug','info','warn','error','critical'], required=False, default='warn', type='str'),
path = dict(aliases=['dest', 'name'], required=False, type='path'),
host = dict(required=False, type='str'),
format = dict(choice=['txt','html'], required=False, default='txt', type='str'),
)
) params = module.params
loglevel = params['level']
host = params['host']
message = params['message']
fmt = params['format'] if params['path']: #if path is none then call function path_logfile() getout tmppath
path = params['path']
else:
path = path_logfile() logger = get_logger(path) logger.setLevel(DIS_LEVEL) if fmt == "txt":
messages = "%s\t%s"%(host,params['message'])
elif fmt == "html":
messages = "%s\t%s<br />"%(host,params['message']) displaymsg = getattr(logger,loglevel)
displaymsg('%s'%messages) #result = dict(changded=True)
return module.exit_json(changed=True)
#return module.exit_json(**result)
if __name__ == '__main__':
main()

ansible的logging模块用来写日志的更多相关文章

  1. logging:不喜欢写日志可不好哦

    logging模块简介 logging模块是python内置的标准模块,主要用于输出程序的运行日志. 可以设置输出日志的等级,日志保存路径,日志文件回滚等等. logging模块的基本使用 impor ...

  2. Python logging模块无法正常输出日志

    废话少说,先上代码 File:logger.conf [formatters] keys=default [formatter_default] format=%(asctime)s - %(name ...

  3. Python模块-logging模块(一)

    logging模块用来写日志文件 有5个级别,debug(),info(),warning(),error()和critical(),级别最高的为critical() debug()为调试模式,inf ...

  4. Python之日志处理(logging模块)

    本节内容 日志相关概念 logging模块简介 使用logging提供的模块级别的函数记录日志 logging模块日志流处理流程 使用logging四大组件记录日志 配置logging的几种方式 向日 ...

  5. 【转】Python之日志处理(logging模块)

    [转]Python之日志处理(logging模块) 本节内容 日志相关概念 logging模块简介 使用logging提供的模块级别的函数记录日志 logging模块日志流处理流程 使用logging ...

  6. Python之日志处理 logging模块

    Python之日志处理(logging模块)   本节内容 日志相关概念 logging模块简介 使用logging提供的模块级别的函数记录日志 logging模块日志流处理流程 使用logging四 ...

  7. logging模块及日志框架

    logging模块及日志框架 logging模块 一.导入方式 import logging 二.作用 写日志 三.模块功能 3.1 经常使用 # V1 import logging logging ...

  8. Python之日志处理(logging模块)转载

    本人主要做一个知识的归类与记录,如是转载类文章,居首都会备注原链接,尊重原创者,谢谢! 此文转载原链接:https://www.cnblogs.com/yyds/p/6901864.html 本节内容 ...

  9. Python之日志处理(logging模块一基础)

    转载自:https://www.cnblogs.com/yyds/p/6901864.html 本节内容 日志相关概念 logging模块简介 使用logging提供的模块级别的函数记录日志 logg ...

随机推荐

  1. spring中设计模式

    MVC模式 Model:pojo.数据库交互(业务数据和业务逻辑) View:Jsp(与用户交互页面) Controller:控制器(接收请求并决定调用哪个模块组件去处理请求,然后决定调用哪个视图(通 ...

  2. Linux NTP时间同步服务

    NTP(Network Time Protocol,网络时间协议)是用来使网络中的各个计算机时间同步的一种协议.它的用途是把计算机的时钟同步到世界协调时UTC,其精度在局域网内可达0.1ms,在互联网 ...

  3. virtual-dom

    virtual-dom的历史 react最早研究virtual-dom,后来react火了之后,大家纷纷研究react的高性能实现,出现了2个流派,一是研究react算法的算法派,(virtual-d ...

  4. makefile $@, $^, $<, $? 表示的意义

    ref:https://www.cnblogs.com/gamesun/p/3323155.html $@  表示目标文件$^  表示所有的依赖文件$<  表示第一个依赖文件$?  表示比目标还 ...

  5. 第五节: Quartz.Net五大构件之Trigger的四大触发类

    一. WithSimpleSchedule(ISimpleTrigger) 1. 用途:时.分.秒上的轮询(和timer类似),实际开发中,该场景占绝大多数. 2. 轮询的种类:永远轮询和限定次数轮询 ...

  6. [再寄小读者之数学篇](2015-06-24 Series)

    (AMM. Problems and Solutions. 2015. 03) Let $\sed{a_n}$ be a monotone decreasing sequence of real nu ...

  7. mysql常见的问题

    1.为什么选择某一个版本 各个版本之间的区别及优缺点 首先,服务器特性 mysql percona mysql mariaDB 开源 开源 开源 支持分区表 支持分区表 支持分区表 innodb Xt ...

  8. java8 list和map的forEach

    list forEach示例 public class HelloWorld { public static void main(String[] args) { List<User> l ...

  9. H5取经之路——随便写点儿

    [相对定位] * 1.使用position:relative:设置元素为相对定位的元素: * 2.定位机制: ①相对于自己原来文档流中的的位置定位,当不指定top等定位值时,不会改变元素位置: ②相对 ...

  10. 计算int数组中的最大,最小,平均值

    public static void testNumber(int[] arr) { int max = arr[0]; int min = arr[0]; int avg = 0; int sum ...