I am very new to java and coding so please understand that I am very naive when it comes to this stuff.
I am trying to get Java to write logs to a .txt file. I have been researching this for hours and my brain hurts too much to keep looking. I am hoping you guys can look at this and tell me what is wrong. Below is the code. This is being written on my Mac for the time being but ultimately I will have it run on Windows.
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.Level;
public class WriteLogEntriesToLogFile extends Login {
public WriteLogEntriesToLogFile(String[] args) throws Exception {
boolean append = true;
FileHandler handler = new FileHandler("Test.logon.log.txt");
Logger logger = Logger.getLogger("/Downloads/log.txt");
logger.addHandler(handler);
logger.severe("severe message");
logger.warning("warning message");
logger.info("info message");
logger.config("config message");
logger.fine("fine message");
logger.finer("finer message");
logger.finest("finest message");
}
}
I definitely feel like I am missing something (or a lot of somethings). Any assistance is appreciated!
From what I could tell your logging was outputting to a file and seemed to be working.
However, I noticed the logs were difficult to parse due to the format being xml-record based, so I used a SimpleFormatter in my solution to read the logs at a line level.
Solution:
public static void main(String[] args) {
Logger logger = Logger.getLogger("");
FileHandler fileHandler;
try {
fileHandler = new FileHandler("Test.logon.log.txt");
logger.addHandler(fileHandler);
SimpleFormatter formatter = new SimpleFormatter();
fileHandler.setFormatter(formatter);
logger.info("0.0 - My first log");
logger.info("1.0 - Test log");
} catch (SecurityException | IOException e) {
e.printStackTrace();
}
}
I hope this helps.
Related
Error here?
It doesn't work out and I cannot get the reason :(
import java.util.logging.Logger;
public class LoggingTest {
public static void main(String[] args) {
String filename = "test.dat";
Logger.getGlobal().info(filename+"opened file");
}
}
I think you should add
java.util.logging.FileHandler
java.util.logging.ConsoleHandler
to
java.util.logging.Logger
or there will be no output in neither console nor log file.
Add this import - import java.util.logging.FileHandler;
Then add file handler before logging info:
FileHandler fileHandler = new FileHandler("test.dat", true);
Logger.getGlobal().addHandler(fileHandler);
I am making an app for android in Qt. So in order to use the Google API I need to implement Java. So I have looked through the QtNotifier example and I am trying to implement the same as a starter.
This Java example comes from the QtNotifier example aswell so it should work the same but it doesn't. I have tried to debug it using the Qt debugger but the breakpoints do not seem to trigger So I added println statements to see at which line it goes wrong. But this is not enough so I am trying to print a stacktrace using a catch/try clause.
I have implemented it like this:
package org.qtproject.qt5.example;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import java.lang.Object;
import java.io.Writer;
import java.io.StringWriter;
import java.io.PrintWriter;
public class NotificationClient extends org.qtproject.qt5.android.bindings.QtActivity
{
private static NotificationManager m_notificationManager;
private static Notification.Builder m_builder;
private static NotificationClient m_instance;
public NotificationClient()
{
System.out.println("it works2222");
m_instance = this;
}
public static void notify(String s)
{
System.out.println(s);
try {
if (m_notificationManager == null) {
System.out.println("1111");
m_notificationManager = (NotificationManager)m_instance.getSystemService(Context.NOTIFICATION_SERVICE);
System.out.println("2222");
m_builder = new Notification.Builder(m_instance);
System.out.println("3333");
m_builder.setContentTitle("A message from Qt!");
System.out.println("4444");
}
System.out.println("5555");
m_builder.setContentText(s);
System.out.println("6666");
m_notificationManager.notify(1, m_builder.build());
System.out.println("7777");
} catch(Exception e) {
StringWriter writer = new StringWriter();
PrintWriter pw = new PrintWriter(writer);
e.printStackTrace(pw);
String errorDetail = writer.toString();
}
}
}
The output is:
I/System.out( 4768): test string
I/System.out( 4768): 1111
It would seem that m_instance is still null because "System.out.println("it works2222");" does not get called. But the error does not get caught.
Is it because this is an error that is not an exception?
I have also tried running the QtNotifier app but the printstatement inside.
public NotificationClient()
{
System.out.println("it works2222");
m_instance = this;
}
But that is also not called in the QtNotifier app.
My question is: How can I trace this error?
In Java, there are both Errors and Exceptions. Normally, an Error is significant enough that your program should just crash and exit. However, for debugging purposes, if you want to catch both you should
catch (Throwable t)
{
t.printStackTrace();
}
to get information on both.
Was able to print some stuff in the logfile by studying and modifying some sample codes but while running the package nothing is being printed to the logfile.
Main Class (Client.java)
public class Client {
static Logger LOGGER = Logger.getLogger(Client.class.getName());
public static void main(String[] args) {
Client logger = new Client();
try {
LogSetup.setup();
emsSession = logger.Initialise();
logger.getAllMEInfo();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Problems with creating the log files");
}
}
private void getAllMEInfo() {
LOGGER.setLevel(Level.INFO);
LOGGER.severe("Info Log");
LOGGER.warning("Info Log");
LOGGER.info("Info Log");
LOGGER.finest("Really not important");
// Some codes for the method
}
}
LogSetup.java
import java.io.IOException;
import java.text.ParseException;
import java.util.logging.ConsoleHandler;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
public class LogSetup {
static private FileHandler fileTxt;
static private LogWriter formatterTxt;
static public void setup() throws IOException, ParseException {
Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
Logger rootLogger = Logger.getLogger("");
Handler[] handlers = rootLogger.getHandlers();
if (handlers[0] instanceof ConsoleHandler) {
logger.removeHandler(handlers[0]);
}
logger.setLevel(Level.SEVERE);
fileTxt = new FileHandler(LogFile.txt");
// create a TXT formatter
formatterTxt = new LogWriter();
fileTxt.setFormatter(formatterTxt);
logger.addHandler(fileTxt);
}
}
LogWriter.java
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
class LogWriter extends Formatter {
public String format(LogRecord rec) {
System.out.println("RECORDING..............");
StringBuffer buf = new StringBuffer(1000);
buf.append(rec.getLevel());
buf.append(calcDate(rec.getMillis()));
buf.append(formatMessage(rec));
return buf.toString();
}
private String calcDate(long millisecs) {
SimpleDateFormat date_format = new SimpleDateFormat("MMM dd,yyyy HH:mm\n");
Date resultdate = new Date(millisecs);
return date_format.format(resultdate);
}
public String getHead(Handler h) {
return ("START " + new Date()) + "\n";
}
public String getTail(Handler h) {
return "END " + new Date() + "\n";
}
}
Log prints the START and END but doesn't even enter in the buff ""RECORDING.............."" so basically nothing is being logged. Any idea???
Please put include statements in your examples so others can try your code.
If you are using java.util.logging, try moving to logback. Logback logging will log properly with no configuration. If you are using java.util.logging then you'll need to find a tutorial on how to configure it, as if it's not configured it doesn't log like you would expect.
The logging framework use a configuration file, where u can set "where and what" to output, for java.util.logging the configuration file is under the folder lib of ure current jvm "/jdk1.x.x/jre/lib/logging.properties" I share my link the problem is in spanish config logging
In short words search the next line and change INFO -> ALL
java.util.logging.ConsoleHandler.level=INFO
java.util.logging.ConsoleHandler.level=ALL
In your code u only need to log message u want, ex:
public class TestLog {
private static final Logger log = Logger.getLogger(TestLog.class.getName());
public static void doLog() {
log.info("info log");
log.fine("fine log");
log.finer("finer log");
.....
log.severe("severe log");
}
}
Always try to use fine, finer or finest for ure debug message, don't use INFO because always print on default config and can slow ure application
I'm new to java and trying to learn how to log an exception by example. I found the following example code here:
http://www.kodejava.org/examples/447.html
However, I don't see where the filename for the log file is specified. When I research the question on Google usually people refer to the framework used for programming java to figure out where the log file gets stored. However, I'm not using a framework. I'm just creating my java files using VIM editor from the command line. The java file sits on an Linux CentOS application server and is called from a client's browser.
Question 1: Is it possible to modify the example below to include a file name and path for logging? Or, am I way off base with this question?
Question 2: Even though I log the exception, will it still propagate to the client for the user to view? Hopefully it will, otherwise the user won't know an error has occurred.
package org.kodejava.example.util.logging;
import java.util.logging.Logger;
import java.util.logging.Level;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
public class LoggingException {
private static Logger logger = Logger.getLogger(LoggingException.class.getName());
public static void main(String[] args) {
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
df.setLenient(false);
try {
//
// Try to parsing a wrong date.
//
Date date = df.parse("12/30/1990");
System.out.println("Date = " + date);
} catch (ParseException e) {
//
// Create a Level.SEVERE logging message
//
if (logger.isLoggable(Level.SEVERE)) {
logger.log(Level.SEVERE, "Error parsing date", e);
}
}
}
}
Try this:
try {
FileHandler handler = new FileHandler("myLogFile.log", true);
Logger logger = Logger.getLogger(LoggingException.class.getName());
logger.addHandler(handler);
} catch (IOException e) {
logger.log(Level.SEVERE, "Error parsing date", e);
}
By default, a file handler overwrites the contents of the log file each time it is created. You might also want to append log file so in FileHandler constructor you need to specify true as a second parameter.
Hope this helps.
EDIT:
package org.kodejava.example.util.logging;
import java.util.logging.Logger;
import java.util.logging.Level;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
public class LoggingException {
private static Logger logger = Logger.getLogger(LoggingException.class.getName());
public static void main(String[] args) {
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
df.setLenient(false);
FileHandler handler = new FileHandler("myLogFile.log", true);
logger.addHandler(handler);
try {
//
// Try to parsing a wrong date.
//
Date date = df.parse("12/30/1990");
System.out.println("Date = " + date);
} catch (ParseException e) {
//
// Create a Level.SEVERE logging message
//
if (logger.isLoggable(Level.SEVERE)) {
logger.log(Level.SEVERE, "Error parsing date", e);
}
}
}
}
This should work. I did not test it.
More efficient way would be create a method to initialize logger and add handler to it. But I will mostly recommend you to think about using log4j. It is easy to set up and widely used logging framework.
You need a FileHandler attached to the log, which you can add manually somewhere in your initialization, or configure your logging with a .properties file.
(p.s. the isLoggable call in this example is redundant and only bloats the code)
Add a file handler for the logger in the config.
Link: http://www.crazysquirrel.com/computing/java/logging.jspx
handlers = java.util.logging.ConsoleHandler, java.util.logging.FileHandler
Better go with log4j. It a good logging framework.
I have a JNLP downloader application deployed on remote user machines that downloads files.
I need to get some error feedback mailed to me. Not so much exceptions, just things getting stuck, or stalled or in infinite loops.
Currently I have a basic handler:
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
public class javaerrorlog {
private static Logger l = Logger.getLogger("");
public static void main(String args[]) throws Exception{
FileHandler handler = new FileHandler("log.txt");
l.addHandler(handler);
l.setLevel(Level.ALL);
l.info("Error logs");
try {
} catch (Error ex) {
l.log(Level.INFO, "", ex);
}
l.fine("");
}
}
Also, should I prompt for the client's permission to send error reporting data?
If you just need notifications you could use something like SMTPHandler. If you need it more fancy you could use JMS with an MDB.