REST JAX-RS记录 [英] REST JAX-RS Logging

查看:149
本文介绍了REST JAX-RS记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遵循了 HelloWorld 示例,成功完成了我的拳头REST.现在,我想在代码中添加日志记录功能.例如,我希望拥有任何日志记录框架(Log4j,JUL)并能够登录代码,并输出到文件中.如何实现对REST代码的日志记录?

I have followed the HelloWorld example and got my fist REST done successfully. Now, I would like to add the logging capability the code. For example, I would like to have any logging frameworks (Log4j, JUL) and be able to log in the code, and have output to a file. How do I implement the logging to my REST code?

@Path("/hello")
public class HelloWorldService {
    Logger log = Logger.getLogger("className");

    @GET
    @Path("/{param}")
    public Response getMsg(@PathParam("param") String msg) {

        String output = "Jersey say : " + msg;

        //for example, here.  hopefully to a file  
        log.info("Log Jersey say : " + msg);

        return Response.status(200).entity(output).build();

    }
}

我正在使用Jersey 1.19,Tomcat 8

I am using Jersey 1.19, Tomcat 8

推荐答案

您可以使用开源Apache Log4j库.在pom中添加以下依赖项,或从此处下载.

You can use open source Apache Log4j library. Add below dependency in your pom or download it from here.

<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

log4j.properties

# Root logger option
log4j.rootLogger=INFO, file

# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender

#Redirect to Tomcat logs folder
#log4j.appender.file.File=${catalina.home}/logs/logging.log

log4j.appender.file.File=C:\\logigng.log
log4j.appender.file.MaxFileSize=10MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

使用此配置,所有日志记录都将重定向到您指定的日志文件.

With this configuration, all logging will be redirected to your specified log file.

来源: http://www.mkyong.com/logging/log4j-log4j-properties-examples/

如何使用Log4j记录消息?

private static final Logger logger = Logger.getLogger(HelloWorldService.class);

记录具有不同优先级的消息,例如debuginfowarnerrorfatal.通常,您只需要使用调试或错误即可.

Logs messages with different priorities, for example, debug, info, warn, error and fatal. Normally, you just need to use debug or error.

//logs a debug message
if(logger.isDebugEnabled()){
    logger.debug("This is debug");
}

//logs an error message with parameter
logger.error("This is error : " + parameter);

//logs an exception thrown from somewhere
logger.error("This is error", exception);

要将记录器设置为debug模式,请在属性文件中进行更改

To set logger in debug mode, change this in your property file

log4j.rootLogger=DEBUG, file

这篇关于REST JAX-RS记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆