Last active
April 6, 2018 19:26
-
-
Save juancarlospaco/3af4d56d73c61994071e to your computer and use it in GitHub Desktop.
Logging Logger for Logs, the best in the world!, Colored, SysLog, Log File, CrossPlatform, Optional Arguments, and more...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
import sys, os | |
import logging as log | |
from copy import copy | |
from tempfile import gettempdir | |
def make_logger(name=str(os.getpid())): | |
"""Build and return a Logging Logger.""" | |
log_file = os.path.join(gettempdir(), str(name).lower().strip() + ".log") | |
log.basicConfig(level=-1, filemode="w", filename=log_file, | |
format="%(levelname)s:%(asctime)s %(message)s %(lineno)s") | |
if not sys.platform.startswith("win") and sys.stderr.isatty(): | |
def add_color_emit_ansi(fn): | |
"""Add methods we need to the class.""" | |
def new(*args): | |
"""Method overload.""" | |
if len(args) == 2: | |
new_args = (args[0], copy(args[1])) | |
else: | |
new_args = (args[0], copy(args[1]), args[2:]) | |
if hasattr(args[0], 'baseFilename'): | |
return fn(*args) | |
levelno = new_args[1].levelno | |
if levelno >= 50: | |
color = '\x1b[31;5;7m\n ' # blinking red with black | |
elif levelno >= 40: | |
color = '\x1b[31m' # red | |
elif levelno >= 30: | |
color = '\x1b[33m' # yellow | |
elif levelno >= 20: | |
color = '\x1b[32m' # green | |
elif levelno >= 10: | |
color = '\x1b[35m' # pink | |
else: | |
color = '\x1b[0m' # normal | |
try: | |
new_args[1].msg = color + str(new_args[1].msg) + ' \x1b[0m' | |
except Exception as reason: | |
print(reason) # Do not use log here. | |
return fn(*new_args) | |
return new | |
# all non-Windows platforms support ANSI Colors so we use them | |
log.StreamHandler.emit = add_color_emit_ansi(log.StreamHandler.emit) | |
a = "/dev/log" if sys.platform.startswith("lin") else "/var/run/syslog" | |
try: # try to Hook Up the SysLog Server if Any. | |
handler = log.handlers.SysLogHandler(address=a) | |
except: # SysLog Server not found | |
log.debug("Unix SysLog Server not found,ignored Logging to SysLog") | |
else: # SysLog Server found, log to it. | |
log.addHandler(handler) | |
else: | |
log.debug("Colored Logs not supported on {0}.".format(sys.platform)) | |
log.getLogger().addHandler(log.StreamHandler(sys.stderr)) | |
log.debug("Logger created with Log file at: {0}.".format(log_file)) | |
return log | |
if __name__ in '__main__': | |
make_logger("your_app_name_here") | |
log.warning(42) | |
log.error(42) | |
log.critical(42) | |
log.info(42) | |
log.debug(42) | |
Author
juancarlospaco
commented
Jun 19, 2015
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment