View Javadoc

1   /*-
2    * #%L
3    * prolobjectlink-jpi-jlog
4    * %%
5    * Copyright (C) 2012 - 2019 Prolobjectlink Project
6    * %%
7    * This program is free software: you can redistribute it and/or modify
8    * it under the terms of the GNU General Public License as
9    * published by the Free Software Foundation, either version 3 of the
10   * License, or (at your option) any later version.
11   * 
12   * This program is distributed in the hope that it will be useful,
13   * but WITHOUT ANY WARRANTY; without even the implied warranty of
14   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   * GNU General Public License for more details.
16   * 
17   * You should have received a copy of the GNU General Public
18   * License along with this program.  If not, see
19   * <http://www.gnu.org/licenses/gpl-3.0.html>.
20   * #L%
21   */
22  package io.github.prolobjectlink.prolog.jlog;
23  
24  import java.io.IOException;
25  import java.text.SimpleDateFormat;
26  import java.util.Date;
27  import java.util.logging.FileHandler;
28  import java.util.logging.Formatter;
29  import java.util.logging.Handler;
30  import java.util.logging.Level;
31  import java.util.logging.Logger;
32  
33  import io.github.prolobjectlink.prolog.AbstractLogger;
34  import io.github.prolobjectlink.prolog.PrologLogger;
35  
36  /**
37   * 
38   * @author Jose Zalacain
39   * @since 1.0
40   */
41  final class JLogLogger extends AbstractLogger implements PrologLogger {
42  
43  	private static final String MESSAGE = "Logger File Handler can't be created";
44  	private static final Logger LOGGER = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
45  
46  	public JLogLogger() {
47  		this(Level.INFO);
48  	}
49  
50  	private JLogLogger(Level level) {
51  		LOGGER.setLevel(level);
52  		Logger rootlogger = LOGGER.getParent();
53  		SimpleDateFormat f = new SimpleDateFormat("yyyy.MM.dd");
54  		String date = f.format(new Date());
55  		Formatter formatter = new JLogFormatter();
56  		for (Handler h : rootlogger.getHandlers()) {
57  			h.setFormatter(formatter);
58  			h.setLevel(level);
59  		}
60  		FileHandler file = null;
61  		try {
62  			file = new FileHandler("%t/prolobjectlink-" + date + ".log", true);
63  		} catch (SecurityException e) {
64  			rootlogger.log(Level.SEVERE, MESSAGE, e);
65  		} catch (IOException e) {
66  			rootlogger.log(Level.SEVERE, MESSAGE, e);
67  		}
68  		assert file != null;
69  		file.setFormatter(formatter);
70  		LOGGER.addHandler(file);
71  	}
72  
73  	public void log(Object sender, Level level, Object message, Throwable throwable) {
74  		LOGGER.log(level, sender + "\n" + message, throwable);
75  	}
76  
77  }