Last active
August 29, 2015 14:13
-
-
Save genba/4904d97bf8050a06a508 to your computer and use it in GitHub Desktop.
This file contains 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
import logging | |
import os | |
SCRIPT_ID = 'name_of_your_script' | |
logger = logging.getLogger(SCRIPT_ID) | |
def setup_logging(filename, loglevel='INFO'): | |
""" | |
Set up logging to a file on disk and with a proper log format. | |
""" | |
# If the user that runs the script has access to /var/log (i.e. user is root), log to system-wide logdir | |
if os.access('/var/log', os.W_OK): | |
logdir = os.path.join('/var/log', SCRIPT_ID) | |
# If user doesn't have access to system-wide logdir, log to a file in their home directory instead | |
else: | |
logdir = os.path.join(os.environ['HOME'], 'logs', SCRIPT_ID) | |
logfile = os.path.join(logdir, filename) | |
# If logdir doesn't exist, create it | |
if not os.path.exists(logdir): | |
os.makedirs(logdir) | |
loglevel = loglevel.upper() | |
supported_loglevels = ['WARNING', 'INFO', 'DEBUG', 'ERROR', 'CRITICAL', 'FATAL'] | |
if loglevel in supported_loglevels: | |
logger.setLevel(getattr(logging, loglevel)) | |
else: | |
raise ValueError('unsupported log level: {}'.format(loglevel)) | |
# Create file handler to log messages to a file on disk | |
fh = logging.FileHandler(logfile) # By default, file is opened in append mode | |
# fh.setLevel(logging.DEBUG) | |
fh.setLevel(loglevel) | |
# Set log message formatter | |
formatter = logging.Formatter('[%(asctime)s] %(levelname)s: %(message)s') | |
fh.setFormatter(formatter) | |
# Add file handler and log formatter to the logger | |
logger.addHandler(fh) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment