[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. python 基本数据类型以及内置方法

    一.数字类型 # 一.整型int # ======================================基本使用====================================== ...

  2. Amazon SNS (Simple Notification Service) Using C# and Visual Studio

    SNS (Amazon Simple Notification Services) Amazon SNS (Amazon Simple Notification Services) is a noti ...

  3. Go语言中的string知识点

    1.Go语言String的本质就是一个[]byte,所以他们之间可以互相转换,byte数组的长度就是字符串的长度. func StringTest1() { str := "Hello,Wo ...

  4. kotlin电商学习记录,好久没来逛逛了

    好久没来,一直做毕业设计,用kotlin写一个基于以图搜图的购物app,现在又赶上实习,内容多,时间少,不过前途光明并由贵人指点.加油 kotlin电商学习记录 技术选型 视图层 kotlin-and ...

  5. Hdoj 1847.Good Luck in CET-4 Everybody! 题解

    Problem Description 大学英语四级考试就要来临了,你是不是在紧张的复习?也许紧张得连短学期的ACM都没工夫练习了,反正我知道的Kiki和Cici都是如此.当然,作为在考场浸润了十几载 ...

  6. BZOJ 1491: [NOI2007]社交网络(Floyd+暴力乱搞)

    题面: https://www.lydsy.com/JudgeOnline/problem.php?id=1491 题解: 先看数据范围,n<=100..欸可以乱搞了 首先因为小学学过的乘法原理 ...

  7. 统计iis日志第一例的次数

    统计iis日志第一例(日期)出现的次数 IIS日志文件格式: #Software: Microsoft Internet Information Services 7.5 #Version: 1.0 ...

  8. module 'pip' has no attribute 'main'

    摘录自:http://www.cnblogs.com/Fordestiny/p/8901100.html 问题分析: 问题解决: 找到安装目录下 helpers/packaging_tool.py文件 ...

  9. DirectX11 With Windows SDK--22 立方体映射:静态天空盒的读取与实现

    前言 这一章我们主要学习由6个纹理所构成的立方体映射,以及用它来实现一个静态天空盒. 但是在此之前先要消除两个误区: 认为这一章的天空盒就是简单的在一个超大立方体的六个面内部贴上天空盒纹理: 认为天空 ...

  10. Python通过分页对数据进行展示

    # 通过分页对数据进行展示 """ 要求: 每页显示10条数据 让用户输入要查看的页面:页码 """ USER_LIST = [] for ...