problems with logging module

Alia Khouri alia_khouri at yahoo.com
Sun Jul 29 17:29:58 EDT 2007


I've been struggling with the logging module in the stdlib which seems
to me rather counter-intuitive:

For some reason it refuses to recognize configuration options when
they are set inside a class so I have had to initialize logging and
set the configuration options in the global scope of my module with
logging.basicConfig.

Here's what I did within the class setup method:

<snip>

self.log = logging.getLogger()

# format
log_format= self.local.format
date_format = self.local.date_format or "%d.%m.%y %H:%M:%S"
self.logfile= self.local.logfile if self.local.log_to_file else None

if self.logfile:
    handler = logging.FileHandler(
        self.logfile, self.local.logfile_mode)
else:
    stream = None # can be sys.st something or other stream
    handler = logging.StreamHandler()

format = logging.Formatter(log_format, date_format)
handler.setFormatter(format)
self.log.addHandler(handler)
self.log.setLevel(self.local.log_level or logging.DEBUG)

</snip>

self.log gets initialized but the formatting options do not get
recognized... this is a pain...

What I do want is something like the log4r module in Ruby:

e.g.

require 'log4r'
require 'getoptlong'
require 'pathname'

class Common
    def init_log
        @log = Log4r::Logger.new(self.class.name)
        @log.add Log4r::Outputter.stdout
        @log.info 'initialized'
    end
end

class Builder < Common
    def initialize(path, options)
        init_log
        if File.exist?(path)
            @path = Pathname.new(path)
            @options = options
        else
            @log.error "not a valid file or directory"
            exit
        end
    end

    def build()
        case @path.ftype
            when 'file'
                filehandlers = {
                    '.txt'  => TxtHandler,
                    '.java' => JavaHandler,
                    '.c'    => CHandler,
                    '.cpp'  => CppHandler,
                    '.py'   => PyHandler,
                    '.pyx'  => PyxHandler,
                    '.exe'  => ExeHandler,
                    '.hs'   => HaskellHandler,
                    '.rb'   => RubyHandler,
                    '.dot'  => DotHandler,
                    '.mp3'  => MP3Handler,
                    '.wav'  => WavHandler,
                    '.csd'  => CSoundHandler,
                    '.orc'  => CSoundHandler,
                    '.sco'  => CSoundHandler,
                }[@path.extname].new(@path, @options).handle()
            when 'directory'
                @log.info "#{@path} is a directory"
        end
    end
end


etc...

still to prefer to code in python though....

Just my 2c...

AK




More information about the Python-list mailing list