It’s extremely useful to add print statements to our code, so we can track down the progress and variables as the code run.
But it get’s dirty and hard to read when lots of print lines run from multiple scripts.
That’s where python built-in logging module comes to the rescue!
in a nut shell, this module is thread safe, supports logging to stdout/shell, files, emails, http and over network.
Check out logging documentation for more: http://docs.python.org/release/2.7/library/logging.html
1 2 3 4 5 6 7 8 9 10 |
import logging ## Setup logging to the print DEBUG and above: logging.basicConfig( level=logging.DEBUG ) ## start logging different levels: logging.debug('log debug line') logging.info('log info line') logging.warning('log warning line') logging.error('log error line') |
Where it’s come really useful is when you need to communicate an error or a message so it won’t get lost!
In some cases you would want to log directly into an email or into s log-file to keep track.
What ever the case is, logging can do it with it’s built-in handlers.
I started cgLogger, an OpenSource wrapper over the build-in logging module, that supports logging in Nuke and Maya using their native commands. This takes advantage of logging messages in a way that will get the artists attention ( or at less more likely to do so ). In many cases it’s very to communicate warning/errors out to the end-user. There for the cgLogger will raise a messageBox for level ERROR and CRITICAL to make sure we have end-user attention.
Code in GitHub:https://github.com/asisudai/cg-logging
This code was inspired by Alex Segal. Thank you Alex.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 |
#!/bin/env python # OpenSource 2013, Asi Soudai - www.asimation.com and Alex Segal # All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # """ Wrapper above built-in python logging module to help logging to Shell, Maya and Nuke directly using time-stamp and logging-level to keep the logs clean. Also, both Maya and Nuke have specific handlers that allow application sepcific logging using warning and popup messages that are native to those applications. fatal and critical levels will pop a warning message in Nuke and Maya to make sure user attention was grabbed when needed. This code was inspired by Alex Segal. Thank you Alex. To use: log = getLogger( 'mylogger' ) log.info( 'log something' ) # Set level to debug log = getLogger( 'mylogger', level=DEBUG ) # OR log = getLogger( 'mylogger' ) log.setLevel( DEBUG ) # Alart user: try: ... do something except Exception, error : log.fatal( "pop up this message if we're in nuke or maya" ) raise error # re raise the error after we msg the user. """ ## ----------------------------------------------------------------------------- # Imports ## ----------------------------------------------------------------------------- import sys import logging ## Inside Maya? try: import maya _in_maya = True except Exception: _in_maya = False ## Inside Nuke? try: import nuke _in_nuke = True except Exception: _in_nuke = False ## ----------------------------------------------------------------------------- # Globals ## ----------------------------------------------------------------------------- MSG_FORMAT = "%(asctime)s %(name)s %(levelname)s : %(message)s" DATE_FORMAT = "%Y-%m-%d %H:%M:%S" # Levels CRITICAL = 50 FATAL = CRITICAL ERROR = 40 WARNING = 30 WARN = WARNING INFO = 20 DEBUG = 10 NOTSET = 0 ## ----------------------------------------------------------------------------- # getLogger - Main call to grab a logger instance ## ----------------------------------------------------------------------------- def getLogger( name, shell=True, maya=_in_maya, nuke=_in_nuke, file=None, level=INFO ): ''' Get logger - mimicing logging.getLogger() usage. name(str) : logger name shell(bol) : output to shell/stdout maya(bol) : output to maya script editor nuke(bol) : output to nuke script editor file(str) : output log into given fullpath-filename level(int) : logger level. default to INFO Example: log = getLogger( 'mylogger' ) log.info( 'log something' ) ''' return Logger( name, shell, maya, nuke, file, level ) ## ----------------------------------------------------------------------------- # Logger Class ## ----------------------------------------------------------------------------- class Logger(object): def __init__( self, name, shell=True, maya=False, nuke=False, file=None, level=INFO ): self._name = name self._log = logging.getLogger(name) self._log.setLevel( level ) ## SafetyCheck - since logging.getLogger support multi threads, if logger ## was already created, it should also have the handlers too. ## so let's avoid creating handlers again, so we won't get ## double handlers... and make a double eveything. if self._log.handlers: # Logger already have handlers, no need to add more. return # Format format = logging.Formatter( MSG_FORMAT, DATE_FORMAT ) # Shell: if shell: stream_hdlr = ShellHandler() stream_hdlr.setFormatter( format ) self._log.addHandler( stream_hdlr ) # File: if file: file_hdlr = logging.FileHandler(file) file_hdlr.setFormatter( format ) self._log.addHandler( file_hdlr ) # Maya: if maya and _in_maya: maya_hdlr = MayaHandler() maya_hdlr.setFormatter( format ) self._log.addHandler( maya_hdlr ) # Nuke: if nuke and _in_nuke: nuke_hdlr = NukeHandler() nuke_hdlr.setFormatter( format ) self._log.addHandler( nuke_hdlr ) def __getattr__(self, attr): ''' expose builtin logger attributes. this won't be needed if I could inherit the logger directly. But the logging.getLoggerClass() don't seem to work without jumping through to many hoops to make it worth it. ''' if hasattr( self._log, attr ): return getattr( self._log, attr ) else: raise AttributeError, "No attribute %s" %attr def __repr__(self): return "%s(%s Level:%i)" % ( self.__class__, self._name, self.level ) ## LEVELS def debug(self, msg): self._log.debug(msg) def info(self, msg): self._log.info(msg) def warning(self, msg): self._log.warning(msg) def error(self, msg): self._log.error(msg) def fatal(self, msg): self._log.fatal(msg) def critical(self, msg): self._log.critical(msg) ## ----------------------------------------------------------------------------- # ShellHandler ## ----------------------------------------------------------------------------- class ShellHandler(logging.Handler): ''' Shell Handler - emits logs to stdout. we'll use sys.__stdout__ to bypass maya and nuke script-editors so they won't show double logging. ''' def __init__(self): logging.Handler.__init__(self) def emit(self, record): sys.__stdout__.write( "%s\n" %self.format(record) ) ## ----------------------------------------------------------------------------- # MayaHandler ## ----------------------------------------------------------------------------- class MayaHandler(logging.Handler): ''' Maya specific handler - will emit warnings using nuke.warning() and critical and fatal levels will popup a warning dialog so artists won't miss important errors. ''' def __init__(self): logging.Handler.__init__(self) def emit(self, record): # Formated message: msg = self.format(record) if record.funcName == "warning": maya.cmds.warning( "\n"+msg ) elif record.funcName in [ "critical", "fatal" ]: ## Emit stdout print: sys.stdout.write("\n"+msg+"\n") ## Open dialog if not in batch mode: if maya.cmds.about( batch=True ) == False: maya.cmds.confirmDialog(title = "A %s have accure" %record.funcName, message = record.message, button = ['Dismiss'], messageAlign = "left") else: sys.stdout.write(msg+"\n") ## ----------------------------------------------------------------------------- # NukeHandler ## ----------------------------------------------------------------------------- class NukeHandler(logging.Handler): ''' Nuke specific handler - will emit warnings using nuke.warning() and critical and fatal levels will popup a warning dialog so artists won't miss important errors. ''' def __init__(self): logging.Handler.__init__(self) def emit(self, record): # Formated message: msg = self.format(record) if record.funcName == "warning": nuke.warning(msg) elif record.funcName in [ "critical", "fatal" ]: nuke.error(msg) nuke.message(record.message) else: sys.stdout.write(msg) ## ----------------------------------------------------------------------------- # let's test it... cause mistakes... happens... from time to time. # __name__ ## ----------------------------------------------------------------------------- if __name__ == '__main__': log = getLogger( "logger_name", shell=True ) log.setLevel( logging.DEBUG ) log.debug('debug') log.info('info') log.warning('warning') log.fatal('fatal') |
One of the biggest advantages of proper logging is that you can categorize messages and turn them on or off depending on what you need. For example, it might be useful to turn on debugging level messages for a certain part of the project, but tone it down for other parts, so as not to be taken over by information overload and to easily concentrate on the task for which you need logging.