Skip to content

Instantly share code, notes, and snippets.

@juancarlospaco
Last active April 6, 2018 19:26
Show Gist options
  • Save juancarlospaco/3af4d56d73c61994071e to your computer and use it in GitHub Desktop.
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...
#!/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)
@juancarlospaco
Copy link
Author

juan@z:~$ python3 temp.py

Unix SysLog Server not found,ignored Logging to SysLog.
Logger created with Log file at: /tmp/your_app_name_here.log.
42
42
42
42
42

juan@z:~$
juan@z:~$ python2 temp.py

Unix SysLog Server not found,ignored Logging to SysLog.
Logger created with Log file at: /tmp/your_app_name_here.log.
42
42
42
42
42

juan@z:~$

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment