开发者

how to print logs in tomcat servlet application

I am creating servlet on Tomcat 6.0 in ubuntu 10.04. For printing log I used System.setOut to redirect output.

System.setOut(new PrintStream(new File("/tmp/new.log")));

System.setErr(new PrintStream(new File("/tmp/new.log")));

I have to use this code in doPost() but when run my application then I am not able to see output thats why temporarily I moved this code in doGet().

When I hit url through browser http://127.0.0.1:8080/hello/hello I am getting following error on browser

java.security.AccessControlException: access denied (java.io.FilePermission /tmp/new1.log read)
    java.security.AccessControlContext.checkPermission(AccessCont开发者_如何学JAVArolContext.java:342)
    java.security.AccessController.checkPermission(AccessController.java:553)
    java.lang.SecurityManager.checkPermission(SecurityManager.java:549)
    java.lang.SecurityManager.checkRead(SecurityManager.java:888)
    java.io.File.exists(File.java:748)
    HelloWorldExample2.doGet(HelloWorldExample2.java:42)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    sun.reflect.GeneratedMethodAccessor32.invoke(Unknown Source)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:616)
    org.apache.catalina.security.SecurityUtil$1.run(SecurityUtil.java:269)
    java.security.AccessController.doPrivileged(Native Method)
    javax.security.auth.Subject.doAsPrivileged(Subject.java:537)
    org.apache.catalina.security.SecurityUtil.execute(SecurityUtil.java:301)
    org.apache.catalina.security.SecurityUtil.doAsPrivilege(SecurityUtil.java:162)**


I'd strongly suggest using a logging framework such as log4j, SLF4j or even the Logging classes that come with Java itself. You're kind of re-inventing the wheel here :)


Use a Logging Framework such as Java Util Logging or Log4J.


Since several diffent servlets might be deployed and each of those could be trying to redirect stdout, this is simply not something tomcat can allow you to do (not to mention it already redirects streams for logging, to catalina.out).

So either just filter out what you need out of the tomcat logfile, or assign those streams to some static variables that you can access from the servlet. You need some synchronisation, though I think the I/O classes might be threadsafe. Using a logging framework would make life easier on you, depending on how big of a project this is (anything bigger than a servlet with 2 methods).


Use slf4j and Logback for your logging needs. You won't regret it since you don't want to reinvent the wheel + you'll have a very customizable solution.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜