This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Logging in servlet Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Logging in servlet" Watch "Logging in servlet" New topic
Author

Logging in servlet

Max Vaha
Greenhorn

Joined: Nov 27, 2007
Posts: 29
Good evening everyone!
I want to log some events in my "HelloWorld" servlet using java.util.logging.Logger (to write "init" to a text file). But I have found only SE examples using Google((.
Can anyone give me an advise?
K.Suresh Kumar
Ranch Hand

Joined: Nov 21, 2007
Posts: 41
Hi,

The following code example will be useful for you.....

Writing Log Records to a Log File
To make a logger write log records to a file, you need to add a file handler to the logger.

try {
// Create a file handler that write log record to a file called my.log
FileHandler handler = new FileHandler("my.log");

// Add to the desired logger
Logger logger = Logger.getLogger("com.mycompany");
logger.addHandler(handler);
} catch (IOException e) {
}

By default, a file handler overwrites the contents of the log file each time it is created. This example creates a file handler that appends.

try {
// Create an appending file handler
boolean append = true;
FileHandler handler = new FileHandler("my.log", append);

// Add to the desired logger
Logger logger = Logger.getLogger("com.mycompany");
logger.addHandler(handler);
} catch (IOException e) {
}


Regards,
Suresh Kumar.K
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14688
    
  16

There's already a log method in the GenericServlet class (which your servlet extends).


[My Blog]
All roads lead to JavaRanch
Max Vaha
Greenhorn

Joined: Nov 27, 2007
Posts: 29
K.Suresh Kumar,
thank you very much! Works perfectly.

Christophe Verre, thanks for your answer, but I need my own log file, GenericServlet is unsuitable for me.
 
GeeCON Prague 2014
 
subject: Logging in servlet