简体   繁体   中英

How to log JAVA Webservice to a file

I build a Service with JAX-RS (Jersey 2.0) and tried to implement a logger who writes down events like errors or results from the requests. Works fine! :) Unfortunately it creates a File every time the service is called but it would be nice that he writes it in one file.

Have a look at my code (it's just the relevant part):

package webservice.feedbacks;

import java.io.IOException;
// imports

@Path("webservice")
public class DeleteFeedback {

Logger logger = Logger.getLogger("Feedbacklogger");
@POST
@Path("/deleteFeedback")
@Consumes(MediaType.APPLICATION_JSON + ";charset=UTF-8")
@Produces("text/plain")
public String setFeedbacks(String incoming){

    FileHandler fh;
    JSONObject jsonObj = new JSONObject(incoming);

    try {
        fh = new FileHandler("D:/Eclipse-Projekte/SmartliveService/logs/DeleteFeedback_log.log");
        logger.addHandler(fh);
        SimpleFormatter formatter = new SimpleFormatter();
        fh.setFormatter(formatter);
        logger.info("----- BEGINN DES PROTOKOLLS -----");
    } catch (SecurityException | IOException e) {e.getMessage();}

    int id = jsonObj.getInt("id");

    String result = executeQuery(id);

    logger.info("----- ENDE DES PROTOKOLLS -----");

    return result;
}

private String executeQuery(int id) {

    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {logger.info("Treiberfehler: " + e.getMessage());}

    Connection con = null;
    Statement stmt = null;

    try{...} catch(SQLException e){
        logger.info("SQL-Fehler: " + e.getMessage());
        return "error";
    } finally {     
        try { if (stmt != null) stmt.close();} catch (Exception e) {logger.info("Das Statement konnte nicht geschlossen werden: " + e.getMessage());};
        try { if (con != null) con.close();} catch (Exception e) {logger.info("Die Verbindung konnte nicht geschlossen werden: " + e.getMessage());};
    }
    return "success";
}
}}

As you can see I created a FileHandler . I got this from a tutorial because I'm not that familiar with JAVA as I had been a few years ago. The code just made a Database-query and sends the results.

So, how do I have to write my code that it logs to one file instead of creating a new one every time the interface is called?

Hope someone can help me.

You should not initialize the filehandler everytime method is called. Maybe you should make it static or initialize it in the constructor. See append also.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM