Python – again
7:46 PM in Programming by Vic Russell
My tasks of late have reacquainted me with the Python programming language. I used it years ago at American Greetings Interactive, and for about two weeks at Humana in Louisville, KY, but little more. The infrastructure where I am currently employed uses Cold Fusion, a tag-based language that is efficient when working with web pages, but I could see little value using it as a sysadmin tool – quick, concise, terse code in the minimum of time is what I needed – Python is the perfect choice.
My passion for the language was reignited after creating script after script in little time. Each script became more ‘pythonic’ and better utilized the compact nature of the language. I again appreciated the indentation over brackets that define a code block – I had to write readable code!
Email and logging were important aspects of the scripts I was writing. I thus utilized the ‘logging‘ class library for log file creation – easy to set up once find the right example. For email, I used smtplib.
Aside: I am not a fan of Pythons documentation – I prefer PHP‘s explain->example style. But, a little digging and venturing to popular Python sites (‘dive into python‘, ‘stack overflow‘, python.org) will eventually produce the result you need.
The logging class is intuitive and has relatively low code overhead. There are more complex ways of configuring the logging class, but for my needs, a simple inline syntax was required. These are sys admin scripts and not part of an application where the time and effort to set up a comprehensive configuration file would be justified.
import logging
# Set up logger logFile = '/path/to/logfile/myLogFileName.log' logging.basicConfig(filename=logFile,format='%(asctime)s %(message)s',level=logging.DEBUG)
That is all that is required to set up a logger. The logfile name can be anything and located anywhere you have read/write privileges.
To use the logger you created, use this command:
logging.info('An informative log message that applies to info status')
That will place an Info entry into the log file defined above.
logging.error('An error message for your app')
logging.debug('Debug info goes here.')
Now there is no excuse not to use log files in your Python applications. Simple. Concise. Intuitive.