ansible的logging模块用来写日志

时间:2024-09-20 10:04:02
[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()