Sunday, January 20, 2008

Customized Logger

Rails framework comes with a logger for you to log activities on your application, which is pretty handy. However, there's a problem. Your development.log or production.log (depends on which environment you are running) comes with many other informations which makes is very difficult to locate your own logs.

In order to solve this issue, we'll create a custom logger which will extend the original logger and save our own logs on a seperate file.

Open environment.rb (the reason we put it there it's because you want it available as soon as your server boots up, so you can call it whenever you need it)

go to the very bottom and add the following lines:

class CustomLogger <>
end

YOUR_CUSTOM_LOG = CustomLogger.new("/path/to/your/log/file")

and you use it just like a regular logger:

YOUR_CUSTOM_LOG.info "GOT HERE"

something worth noting is that the variable that holds the CustomLogger object must be
a global variable, or else you won't be able to access it in your controllers or models.

another thing is that make sure you create the log file ahead of time, your server won't start if the log file you specified does not exist.

when everything is set, restart your server and test it out!


J

No comments: