博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ansible的logging模块用来写日志
阅读量:5925 次
发布时间:2019-06-19

本文共 2796 字,大约阅读时间需要 9 分钟。

[root@node-1 library]# cat dolog.py #!/bin/env pythonANSIBLE_METADATA =  { 'metadata_version': 'alpha',            'status': ['preview'],            'supported_by': 'lin.wang',            'release_date': '2018-05-09'}DEOCUMENTATION = """---module: dologversion_added: "1.0"short_descriptions: logging with log leveldescription:     - 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 Playbooksdolog: message: "xxxxxxxxx." path: "{
{ logfile }}" host: "{
{ hostname }}" format: "{
{ LOGFMT }}"delegate_to: localhost """import osimport timeimport loggingfrom ansible.module_utils.basic import AnsibleModuledate = 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 pathdef 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 retdef 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
"%(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()

 

转载于:https://www.cnblogs.com/wangl-blog/p/9019809.html

你可能感兴趣的文章
网络营销与电子商务
查看>>
可输入的模糊搜索ComBox控件
查看>>
MySQL 5.6为什么关闭元数据统计信息自动更新&统计信息收集源代码探索
查看>>
Linux 下mysql永久更改字符集
查看>>
apache prefork模式优化错误
查看>>
jmeter高级用法例子,如何扩展自定义函数
查看>>
lvs
查看>>
通过jsp请求Servlet来操作HBASE
查看>>
JS页面刷新保持数据不丢失
查看>>
最浅显易懂的数据库索引讲解
查看>>
清橙A1202&Bzoj2201:彩色圆环
查看>>
使用data pump工具的准备
查看>>
springMVC---级联属性
查看>>
get和post区别
查看>>
是机遇还是挑战?---浅谈谷歌收购摩托罗拉移动
查看>>
项目总结26:java调用webservice接口(asmx)
查看>>
crontab执行shell脚本日志中出现乱码
查看>>
基于HTML5手机上下滑动翻页特效
查看>>
打造自己博客(wordpress)的wap手机版本
查看>>
Floodlight 在 ChannelPipeline 图
查看>>