a4cb5cae2521266b834fe15899ebd37341ed885a
1#
2# __main__.py
3#
4# This module is the entrypoint of the `logparse` shell command and also
5# contains single-use functions which don't fit elsewhere.
6#
7
8import logging, logging.handlers
9import argparse
10import os
11import glob
12import sys
13from datetime import datetime
14
15import logparse
16from .config import *
17from logparse import formatting, mail, config
18from .parsers import load_parsers
19
20def rotate():
21 # rotate logs using systemd logrotate
22 if argparser.parse_args().function is None:
23 if (prefs['rotate'] == 'y'):
24 subprocess.call("/usr/sbin/logrotate -f /etc/logrotate.conf", shell=True)
25 logger.info("rotated logfiles")
26 else:
27 logger.debug("user doesn't want to rotate logs")
28 if (prefs['rotate'] == 's'):
29 logger.debug("Here is the output of `logrotate -d /etc/logrotate.conf` (simulated):")
30 sim = subprocess.check_output("/usr/sbin/logrotate -d /etc/logrotate.conf", shell=True)
31 logger.debug(sim)
32
33
34
35def main():
36 # Get arguments
37 argparser = argparse.ArgumentParser(description='grab logs of some common services and send them by email')
38 argparser.add_argument('-t','--to', help='mail recipient (\"to\" address)', required=False)
39 argparser.add_argument('-c', '--config', help='path to config file', required=False)
40 argparser.add_argument('-p', '--print', help='print HTML to stdout', required=False, dest='printout', action='store_true', default=False)
41 argparser.add_argument('-d', '--destination', help='file to output HTML', required=False)
42 argparser.add_argument('-f', '--overwrite', help='force overwrite an existing output file', required=False, action='store_true', default=False)
43 argparser.add_argument('-v', '--verbose', help='verbose console/syslog output (for debugging)', required=False, default=False, action='store_true')
44 argparser.add_argument('-r', '--rotate', help='force rotate log files using systemd logrotate', required=False, default=False, action='store_true')
45 argparser.add_argument('-nr', '--no-rotate', help='do not rotate logfiles (overrides logparse.conf)', required=False, default=False, action='store_true')
46 argparser.add_argument('-l', '--logs', help='services to analyse', required=False)
47 argparser.add_argument('-nl', '--ignore-logs', help='skip these services (takes precedence over -l)', required=False)
48 argparser.add_argument('-es', '--embed-styles', help='make CSS rules inline rather than linking the file', required=False, default=False, action='store_true')
49 argparser.add_argument('-nh', '--plain', help='write/send plain text rather than HTML', required = False, default=False, action='store_true')
50
51 # Load config
52 if argparser.parse_args().config:
53 config.prefs = config.loadconf(argparser.parse_args().config, argparser)
54 else:
55 config.prefs = config.loadconf(argparser=argparser)
56 prefs = config.prefs
57
58 # Set up logging
59 logger = logging.getLogger(__name__)
60 loghandler = logging.handlers.SysLogHandler(address = '/dev/log')
61 loghandler.setFormatter(logging.Formatter(fmt='logparse.py[' + str(os.getpid()) + ']: %(message)s'))
62 loghandler.setLevel(logging.WARNING) # don't spam syslog with debug messages
63 if argparser.parse_args().verbose or (config.prefs['verbose'] == 'y' or config.prefs['verbose'] == 'yes'):
64 logging.basicConfig(level=logging.DEBUG)
65 logger.debug("Verbose mode turned on")
66 else:
67 logging.basicConfig(level=logging.INFO)
68 logger.addHandler(loghandler)
69
70 logger.debug("Finished loading config")
71
72 # Time analysis
73 global start
74 start = datetime.now()
75 logger.info("Beginning log analysis at {0} {1}".format(start.strftime(formatting.DATEFMT), start.strftime(formatting.TIMEFMT)))
76 logger.debug("This is {0} version {1}, running on Python {2}".format(logparse.__name__, logparse.__version__, sys.version.replace('\n', '')))
77
78 # Write header
79
80 global output
81 if argparser.parse_args().plain:
82 output = formatting.PlaintextOutput(linewidth=prefs['linewidth'])
83 else:
84 output = formatting.HtmlOutput()
85
86 output.append_header(prefs['header'])
87
88 # Find parsers
89
90 parser_providers = []
91 if argparser.parse_args().logs:
92 log_src = argparser.parse_args().logs.split()
93 elif len(prefs['parsers']) > 0:
94 log_src = prefs['parsers']
95 else:
96 log_src = load_parsers.default_parsers
97
98 for parser_name in log_src:
99 parser = load_parsers.search(parser_name)
100 if parser == None:
101 logger.warning("Can't find parser {0}".format(parser_name))
102 continue
103 else:
104 parser_providers.append(load_parsers.load(parser))
105
106 if argparser.parse_args().ignore_logs or len(prefs['ignore-parsers']) > 0:
107 if argparser.parse_args().ignore_logs:
108 ignore_src = argparser.parse_args().ignore_logs.split()
109 else:
110 ignore_src = prefs['ignore-parsers']
111 for parser_name in ignore_src:
112 if parser_name in [x.__name__.rpartition('.')[2] for x in parser_providers]:
113 logger.info("Ignoring default parser {0}".format(parser_name))
114 parser_providers_new = []
115 for p in parser_providers:
116 if p.__name__.rpartition('.')[2] != parser_name:
117 parser_providers_new.append(p)
118 parser_providers = parser_providers_new
119 continue
120
121 # Execute parsers
122
123 logger.debug(str(parser_providers))
124 for parser in parser_providers:
125 output.append_section(parser.parse_log())
126
127 # Write HTML footer
128 output.append_footer()
129
130 if argparser.parse_args().printout:
131 print(output)
132 if argparser.parse_args().destination or prefs['output']:
133 if argparser.parse_args().destination:
134 dest_path = argparser.parse_args().destination
135 else:
136 dest_path = prefs['output']
137 logger.debug("Outputting to {0}".format(dest_path))
138 if (argparser.parse_args().embed_styles or prefs['embed-styles']) and not (argparser.parse_args().plain or prefs['plain']):
139 output.embed_css(prefs['css'])
140 if (not os.path.isfile(dest_path)) and not (argparser.parse_args().overwrite or config['overwrite']):
141 output.write(dest_path)
142 else:
143 logger.warning("Destination file already exists")
144 if input("Would you like to overwrite {0}? (y/n) [n] ".format(dest_path)) == 'y':
145 output.write(dest_path)
146 else:
147 logger.warning("No output written")
148
149 if argparser.parse_args().to or prefs['mail']['to']:
150 if argparser.parse_args().to:
151 to = argparser.parse_args().to
152 else:
153 to = prefs['mail']['to']
154 mail.sendmail(mailbin=prefs['mail']['mailbin'], body=(output.embed_css(prefs['css']) if isinstance(output, formatting.HtmlOutput) else output.content), recipient=to, subject=formatting.fsubject(config.prefs['mail']['subject']), html=isinstance(output, formatting.HtmlOutput))
155
156 # Print end message
157 finish = datetime.now()
158 logger.info("Finished parsing logs at {0} {1} (total time: {2})".format(finish.strftime(formatting.DATEFMT), finish.strftime(formatting.TIMEFMT), finish - start))
159
160 return