Options

Python 3 Logging (neteng, devops)

DexterParkDexterPark Member Posts: 121
Check out the full repo: https://github.com/ddexterpark/devops/


[HTML]"""Dexter's Device Logger Utility, Version 1.0, by Dexter Park.
Learn more: https://github.com/ddexterpark/devops"""

import logging, sys, time, datetime

# Display timestamp.
def timestamp():
format_time = "on {:%a, %d %b %Y at %I.%M%p}, PST".format(datetime.datetime.now())
return format_time

# Creates a root logger for monitoring your program's events.
fileLogger = logging.getLogger()
fileLogger.setLevel(logging.DEBUG)

# Dictionary for filtering log messages by severity.
logMessages = {'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL}

# Call the console handler when you only want to see log messages in your terminal window.
def console(setLevel):
# Formats the console messages
consoleFormatStr = "[%(asctime)s, %(threadName)s, %(levelname)s] %(message)s"

# Stream Handler for stdout, stderr
consoleFormatter = logging.Formatter(consoleFormatStr)
consoleHandler = logging.StreamHandler(sys.stdout)
consoleHandler.setFormatter(consoleFormatter)

# Switch for filtering console log messages.
filterConsoleHandler = logMessages.get(setLevel, logging.DEBUG)
consoleHandler.setLevel(filterConsoleHandler)

#consoleHandler.setLevel(setLevel)
fileLogger.addHandler(consoleHandler)

# Call setup handler when you want to see log messages in your terminal window AND save the output to a file.
def setup(logFile, setLevel):
global fileLogger
logFormatStr = "[%(asctime)s %(threadName)s, %(levelname)s] %(message)s"

# File Handler for log file
logFormatter = logging.Formatter(logFormatStr)
fileHandler = logging.FileHandler(logFile)
fileHandler.setFormatter(logFormatter)

# Switch for filtering file handler messages.
filterFileHandler = logMessages.get(setLevel, logging.DEBUG)

fileHandler.setLevel(filterFileHandler)
fileLogger.addHandler(fileHandler)

# Stream Handler for console (stdout, stderr)
console(setLevel)

# Call event when you want to create log messages regardless of which handler you prefer.
# Example: ddlog.event('[+] test message', 'info')
def event( string, level='debug'):
switchLogLevels = {'debug': fileLogger.debug,'info': fileLogger.info,'warning': fileLogger.warning,
'error': fileLogger.error, 'critical': fileLogger.critical}
switchLogLevels[level](string)
[/HTML]


EXAMPLE OF HOW TO USE:

[HTML]import ddlogin

# Option for logging.
path = os.getcwd() + '//logs/'
file = hostlist +' '+ ddlog.timestamp()+'.log'
if not os.path.exists(path):
os.makedirs(path)
if output is True:
ddlog.setup(path+file, 'info')
else:
ddlog.console('info')

# Use 1
ddlog.event("[-] Failed to Authenticate.",'error')

# Use 2
for command in commands:
stdin, stdout, stderr = ssh.exec_command(command, get_pty=True)
lines = iter(stdout.readline, "")
for line in lines:
ddlog.event('[OUTPUT] '+line,'info')
stdin.close()
[/HTML]
My advice to anyone looking to advance their career would be to learn DevOps tools and methodologies. Learn how to write code in languages like Python and JavaScript. Not to be a programmer, but a network automation specialist who can do the job of 10 engineers in 1/3 of the time. Create a GitHub account, download PyCharm, play with Ansible, Chef, or Puppet. Automation isn't the future, it's here today and the landscape is changing dramatically.
Sign In or Register to comment.