ZZzzZZzz
ZZzzZZzz

Reputation: 1844

How to use log4j in REST Service

I have tried using log4j in REST client and it logs the information. However, I have tried to log the events server side using log4j and it dose not record any logs. Here is my sample where I have used on my server side.

 @POST
    @Path("/send")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public Response consumeJSON(String str) throws Exception {
     AmazonKinesisRecordProducerSample.init();

     try {

            pushData(str);

            LOG.info(str)

        } catch (IOException e) {
            e.printStackTrace();
            LOG.info(""+e);
            return Response.status(400).entity(e).build();
        }

        return Response.status(200).entity(d).build();
    }

Here is my client code. This captures the logs.

public class JerseyClient {
private static final Logger LOG = Logger.getLogger(JerseyClient.class);
static Date date = new Date();
public static void main(String[] args) {
    try {
        int i = 0;
        long createTime = System.currentTimeMillis();
        System.out.println("Server Response");
        for (i = 0; i < 1000; i++) {
            Details d = new Details();
            ClientConfig clientConfig = new DefaultClientConfig();
            clientConfig.getFeatures().put(
                JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
            Client client = Client.create(clientConfig);
            WebResource webResource = client
                .resource("http://localhost:8080/JerseyJSON/rest/jsonServices/send");

            ClientResponse response = webResource.accept("application/json")
                .type("application/json").post(ClientResponse.class, d);
            if (response.getStatus() != 200) {
                throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
            }
            String output = response.getEntity(String.class);
            LOG.info(output + "  inserted at-%d  " + createTime);
            System.out.println(output);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

This captures the log in TestLog.log under my project root directory. But, my server side code which is the POST method, this is running on the Tomcat is not capturing the logs.

Here is my log4j.xml for reference.

<?xml version="1.0" encoding="UTF-8"?>

<!-- Appenders -->

<appender name="console" class="org.apache.log4j.ConsoleAppender">
    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="%d{HH:mm:ss} [%t] %c{1} - %m%n" />
    </layout>
</appender>

<appender name="ROLL" class="org.apache.log4j.RollingFileAppender">
    <param name="File" value="Testlog.log" />
    <param name="Append" value="true" />
    <param name="Encoding" value="UTF-8" />
    <param name="MaxFileSize" value="10MB" />
    <param name="MaxBackupIndex" value="2" />

    <layout class="org.apache.log4j.PatternLayout">
        <!-- The default pattern: Date Priority [Category] Message\n -->
        <param name="ConversionPattern"
            value="%d{yyyy-MM-dd HH:mm:ss,SSSZ} %-5r %-5p [%c{1}] (%t:%x) %m%n" />
    </layout>   
</appender>

<category name="com.java" additivity="false">
    <priority value="DEBUG"/>
    <priority value="INFO" />
    <appender-ref ref="ROLL"/>
    <appender-ref ref="CONSOLE"/>
</category>

<root>
    <priority value="INFO" />
    <appender-ref ref="CONSOLE" />
    <appender-ref ref="ROLL"/>
</root>

Upvotes: 1

Views: 8888

Answers (3)

Dheeraj kumar
Dheeraj kumar

Reputation: 77

Maven Dependency

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

Controller Class

@RestController
@RequestMapping(value = "/userinfo")
public class UserController {


    @Autowired
    private UserService userService;

    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    // get all userinfo
    @GetMapping(value = "/alluser", produces = MediaType.APPLICATION_JSON_VALUE)
    public List<UserDto> getUserinfo() {
        LOGGER.info("inside class!!!! UserController, method!!!: getUserinfo");
        return userService.getAllUserInfo();
    }

    // get user info by id
    @GetMapping(value = "/{userId}", produces = MediaType.APPLICATION_JSON_VALUE)
    public UserDto getUserById(@PathVariable("userId") String userId) {
        LOGGER.info("inside method!!!: getUserById", userId);
        return userService.getUserByUserId(userId);
    }
}

For all java code and reference use below link:

https://www.youtube.com/watch?v=n4X99F6ckhw&t=4s

Upvotes: 0

RPresle
RPresle

Reputation: 2561

Please refer to the documentation on how to do an helloWorld

It seems you are mixing several Log package. Be sure to use Log4J and not the Java Logger. They have different syntax.

Then, in your code, I see several problems. In your try, you're calling for a new instance of Logger, getLogger is not a logging method. In your catch block, do not use "" + e to log your exception, use the library ability to log all the exception object including message and stackTrace.

EDIT:

Finally we found the answer. There is two project: client side with a main, and server side with REST service, with one log config for both. The problem was that the client side was logging in the local directory whereas the server side was logging in the Tomcat Directory.

Upvotes: 1

Nikolay Rusev
Nikolay Rusev

Reputation: 4230

May be you are missing to include log4j.properties or log4j.xml in your classpath.

Upvotes: 1

Related Questions