Nick jj
Nick jj

Reputation: 23

Disable showing logs on console programmatically

I want to disable showing logs on command prompt but rather writing in it to log file which I have implemented. I am using java.util.logging.Logger

      public class test{
          static Handler fileHandler = null;
      private static Logger logger = Logger.getLogger(Test.class.getName());
       public static void main(String args[]){

          Path path = Paths.get(PATH,"logfile.log");
         logger.log(Level.INFO, "Using Scanner for Getting Input from User");
         fileHandler = new FileHandler(path.toString(), true);  
          fileHandler.setFormatter(new SimpleFormatter());
           logger.addHandler(fileHandler);

      }
     }

Thanks in advance

Upvotes: 0

Views: 896

Answers (1)

Programmerabc
Programmerabc

Reputation: 327

Use this method to log message make sure to set file path properly and use logger.info("Log message") to log messages:

public static void log(String filepath){
      Logger logger = Logger.getLogger("MyLog");  
      FileHandler fh;
      logger.setUseParentHandlers(false);//Use this to not show output in command line

    try {  

        fh = new FileHandler(filepath);  
        logger.addHandler(fh);
        SimpleFormatter formatter = new SimpleFormatter();  
        fh.setFormatter(formatter);  

        logger.info("My first log");//Use this to log statement

    } catch (SecurityException e) {  
        e.printStackTrace();  
    } catch (IOException e) {  
        e.printStackTrace();  
    }  
}

Upvotes: 1

Related Questions