[back to the tutorial]   [previous session]   [next session]  

logging to file

actually the name of this paragraph is misleading. a more correct name would be handling to file, since it's a handler and not a logger that is actually writing some representation of your logrecords to a file.

to make sure log records are sent to a file, you choose a logger and attach to it a handler with action a function that writes to your file. the logging package exports the commodity function writeToFile for this purpouse. the name of the file is given as an extra parameter in the call to addHandler.

recall that both loggers and handlers have a level. records at a specific severity are examined by loggers first; if the severity is higher than the level of the logger, they are offered to all of the attached handlers. handlers will again check the level of the record before taking action. in the following example we make sure absolutely all logrecords are examined by initializing the root logger at the FINEST level. the level of the basic_stdout console handler is not affected.

R> logReset()
R> basicConfig(level='FINEST')
R> addHandler(writeToFile, file="~/testing.log", level='DEBUG')
R> with(getLogger(), names(handlers))
[1] "basic.stdout" "writeToFile"
R> loginfo('test %d', 1)
2010-04-07 11:31:06 INFO::test 1
R> logdebug('test %d', 2)
R> logwarn('test %d', 3)
2010-04-07 11:31:15 WARN::test 3
R> logfinest('test %d', 4)

if the file was not existing or empty, this would be its content after the above steps:

2010-04-07 11:31:06 INFO::test 1
2010-04-07 11:31:11 DEBUG::test 2
2010-04-07 11:31:15 WARN::test 3

all log records have been passed to both handlers basic.stdout and writeToFile. the default console handler has handled records with severity at or above INFO, our file handler had threshold DEBUG so it handled also the second record in the example session. the fourth record was dropped by both handlers.