I've written a console app in Java, that uses Google Protocol Buffers for serialization.
However, when that code is used, during library loading, it outputs some warnings about illegal reflective access operations.
AFAIK, that's some minor Google annoyance that doesn't really affect anything, so I would like my app not to dump that trash to output.
At the same time, I obviously want my app to output its own stuff as normal.
How does one generally go about things like this?
What would be a good way to handle this concrete situation?
The best way would be to add a logger and not use the standard console output. You can read about slf4j. It has many advantages over the standard output. You can have different levels of the log you want to see - info,debug,warn,error etc. So you can limit the amount of information you read. Also you will keep previous outputs in files and also you can configure different appenders - so different classes write their outputs into different files.
Basically this is the preferred way for most java applications and there is a reason why
Related
Why is it a good practice to use logger.debug() instead of System.out.println()?
I understand that log4j allows you to control what you wish to print (DEBUG,FATAL,INFO, etc), but apart from that, is there any other benefit?
A Logger adds so much more value to your logging.
Log levels: In a production environment you don't care about some levels (ex: debug info), only serious errors and system crashes.
Log filtering: Filter what components are allowed to log.
Log formatting: Control the information and its format contained in the log. You can setup defaults (like time and thread id) or add more specific ones per statement.
The log destination: You can set up your logger to write to a file, to emails, to databases, etc.
A policy for keeping and archiving logs: Let the logger manage the logs, keep some history, delete older
Also, Loggers are usually synchronized, so your print statements aren't written over eachother. You cannot guarantee that with System.out.
You can implement all this with System.out, but it would be so complex and tedious.
If your code is ever used in a web service or a system service, using debug statements will ensure that they appear in the services logs. If not you risk them being printed to a hidden console window and being lost.
Specialized loggers offer a number of benefits over plain standard output:
logical separation of logging, in at least two orthogonal areas: subsystem and importance
flexibility - there are many predefined ways to output and store log data, and you can roll you own, if you really want
configurability - you can precisely control what and where to log, and all of this is external to the code that actually uses logging, making it simple and inobtrusive
formatting - you don't need to manually append all the bookkeeping information, such as the class name, time etc. Logger does that for you, in an entirely configurable way, allowing you to write simple, clear logging code and retain all the benefits, like filtering and precise information.
speed - loggers are optimized not to introduce much overhead
My application has to output content for the user. Throughout all my classes I've just been using System.out.println, but since the program isn't intended to be run by command line this isn't really suitable.
I had thought of simply making a classes that extends JPanel and having all the content append to a textarea. I've been reading that this isn't a good move, and an issue arises in that I'll have to pass the JPanel class to all the classes that output text.
Is there a good-practice alternative to System.out.println? If not, how do you suggest I proceed? I have suggestions of Java Logging, but I don't want to output to a file.
You should have limited user interaction in most of your classes and in fact the UI code should be separate in its own set of class. You should strive to write your model (non-UI) code so that it can work well in a console application, a Swing application, an SWT application or other UI library type application. This way your code can work with SOP or with GUI's as you see fit. I will wager that > 90% of Java classes created by professional coders have no UI code within them.
Also please note that logging and user interaction code are two completely orthogonal concepts. I look at logging as a way to communicate with the developer and supporter, not the user.
Agree with #Hovercraft's comment. Don't pass the JPanel, have a static method in your UI class that all other objects call when they need to output. That method will handle formatting and appending and all that.
Moreover there isn't really an alternative to println when it comes to Java. That's because println only outputs to stdout and in a GUI application it's hidden unless the user executes your program from command line.
What you want is a configurable logging framework, like Log4j. By writing a custom log appender, you have have your log output appear anywhere you want, not just in a file: http://www.javaworld.com/javaworld/jw-12-2004/jw-1220-toolbox.html
The reason is that sending messages to stdout is usually inappropriate in a production environment. If you're coding a library, the library should return information to its caller, not print to stdout. If you're coding a GUI app, the information should be presented to the user, not to where stdout happens to be pointing (which might be nowhere). If you're coding a server (or something that runs in a server-side container) you should be using whatever logging facility the framework has provided. And so forth.
The logger gives to ability to define different levels of importance of the logged messages and the ability to use different sink for the output - the console, a file, etc.
Also it's easy to enable or disable only some type of message when using a logger - for example you don't want to see every debug message in production.
I don't think that using loggers offers any significant advantages in unit tests, but I'd prefer it even there anyways. In unit tests asserts are usually my primary concern.
Btw you should really consider using something like Commons Logging or SLF4J as a log framework facade - it's bad style to tie your code to a specific logging framework. Common Logging and SLF4J make it easy to switch logging frameworks if you choose to.
The best method to output information to your user depends on the kind of app you're working on.
If your app is batch-oriented and highly technical, it might be appropriate to send output to a scrolling text area (JTextArea) so users can view the latest status and scroll back to get details if they want.
But if it's more interactive and less technical in nature, you should try to minimize output to only the most essential things, like high-level status messages, or critical error messages. Simple dialogues (JOptionPane) and status bars (JLabel) might be best in that case.
In either case, if your app is large, you should consider designing it so that you don't scatter a lot of UI code in with everything else. Keeping the main logic separate from the presentation code will help with maintenance later on. One well-accepted approach to doing that is called model-view-controller (MVC).
Here are a couple good links to get you started on MVC.
Wikipedia article on Model-view-controller
Stackoverflow question: The MVC pattern and SWING
Is there a good-practice alternative to System.out.println?
return
The program I'm building seems to freeze at some points on the user's system. When I test the very same steps, I see no problem. Even though Java is supposed to be a platform-independent VM, my guess is it has to do with the systems we're using (I'm on linux, the user on Mac), maybe something with file access.
I cannot access the user's system, and the user has no idea what debugging means. In order to test where the problem is, I was thinking of writing the program's progress to a file, and having him send me the file when there's a problem. Therefore my question:
Is there some kind of library which allows writing the line by line execution of a program to a file? Ideally, the values of certain variables would also be included.
edit: I'm familiar with Logger, but (like one answer says), that would require writing a lot of log statements. Is there some way to do this automatic? Maybe line by line is overkill, but something like log each method entry/exit would definitely work.
Thanks a lot!
This might be a good use case for aspect-oriented programming. Specifically, the AspectJ library for Java might suit your needs (there are others, but this is the one I'm most familiar with). You could define a logging aspect that would automatically insert method entry/exit log messages into the methods you wish to trace, without having to modify the code for those methods. The aspect can be included or excluded as you wish whenever you build the application (eg, include it just for this user until you resolve the issue).
Something like the following might be a good start:
aspect LogAllMethods {
Log log = new Log(); // pseudocode -- replace with whatever logging mechanism you like
before(): call(public * com.mycompany.*.*(..)) {
log.log("Entered method: " + thisJoinPoint);
}
after(): call(public * com.mycomapny.*.*(..)) {
log.log("Leaving method: " + thisJoinPoint);
}
}
This basically says that, before and after any public method call in the package com.mycompany, log the entry/exit and the name of the method (thisJoinPoint is a special variable in AspectJ that refers to the point in the program's execution that the aspect is being applied to). The AspectJ documentation has some nice tutorials and examples of defining aspects and how they can be used, as well as instructions on how to introduce aspects into your application.
This might be overkill for your situation and underutilization of AspectJ, but it should allow you to do some fine-grained debugging without having to add logging calls to every method in your code.
Typically the debug information you want would be included in a log file. Logging frameworks like Java's built in Logging API allow you to configure what severity of messages to produce when the program is run. In other words, you could have it normally report severe errors only, but enable debug output selectively when you need more information.
However, logging frameworks normally require you, the programmer, to explicitly tell it what to log. It doesn't simply log everything (that would be a lot of data too!).
It sounds like what you want is logging in your application. See the Wikipedia article for Java Logging Frameworks for details.
Some of the more common logging frameworks, all mentioned in the aforementioned article, are:
Log4J
Java Logging API
Apache Commons Logging
SLF4J
I have a Java program which runs as 3 separate processes on the same server. I would like all of the processes to share a single log file, is there a way to specify that in a logging.properties file? I am using java.util.logging to handle logging.
Currently, this is how I define my FileHandler in my logging.properties file:
java.util.logging.FileHandler.pattern=%h/log/logfile.log
This works fine for 1 instance of the program, however, if I attempt to start 3 separate instances of the program the result is:
logfile.log
logfile.log.1
logfile.log.2
Any advice on this?
Thankyou
Logback is another logger, but it supports your case.
from the docs: http://logback.qos.ch/manual/appenders.html
check out prudent mode for FileAppender
Writing to the same file from different processes (the different JVMs) is not recommended.
The only safe way to do it is to somehow lock the file, open it, write to it and then close it. This considerably slows down each writing, which is generally deemed unacceptable for a logger. If you really want to go this way, you can always write your own handler.
I would write a 2nd Java program - a logger. Have the other processes send log messages to the logging program, which would then write to the single log file. You can communicate between the programs using sockets. Here's an example of how to do that.
Paul
Elaborating on Paul's answer, you can use a SocketHandler to direct the log events from all processes to a single process, which actually writes to a file.
Most log packages provide a simple implementation of this functionality. Another widely supported option is integration with the system's logging facility (Window's Event Log or syslogd).
I want to log information to a file and want to know is there any advantage in using the Java Logger class versus my own personal method of logging?
I know using a logger I just add my own FileHandler to the logger. My personal method is just using a FileOutputStream.
Honestly your logger may be as good, it's pretty easy to put in log levels, filtering, etc.
The problem is when you start to put together code from 10 different groups each with their own logging. Some use System.out, some use some custom logger, some use log4j, ...
How do you parse or redirect the output? How do you filter all that output to just show your messages (For instance, filtering options in log4j won't prevent messages being sent straight to System.out).
It's a pretty big bulk change depending on which system you are moving from/to. Better just to use one very common one from the beginning and hope that it's the one everybody else on the project chooses.
The real question is: why would you bother writing your own logger when there are already existing libraries for doing that? Does your logger do something that the others don't? I kind of doubt it.
Standardization is another big issue - see Bill K's answer.
For most scenarios, a standard logging framework is the way to go. They are pretty flexible. But using your own implementation can also be a valid option, specially if we are not speaking of traditional logging (global debugging, problems, warning messages) but about specific informational meesages or accounting.
Among other factors, bear in mind that the standarization of logging allows third party libraries to cooperate. For example, if you have a standard web application using (say) Hibernate, and you have configured a standard Java logging lib, then you can not only log from your own code but also tell Hibernate to log debugging info to your log files (not necessarily the same files). That is very useful - almost a must.
If you code your own logging library with a plain FileOutputStream, you must decide -among other things- if you are going to keep the file opened, or reopen-append-close in each write - and you must take of synchronization and related issues. Nothing terribly complicated, though.
The logger gives to ability to define different levels of importance of the logged messages and the ability to use different sink for the output - the console, a file, etc.
Also it's easy to enable or disable only some type of message when using a logger - for example you don't want to see every debug message in production.
A logging framework allows you specify logging levels (e.g. log only critical messages, log only debug messages etc.). It also allows you to log to multiple destinations (e.g. to a file, to syslog etc.) and you can do this even after your application is fully built by just changing a config file and not changing any code. It can also format your logs easily depending on various parameters.
There are numerous other advantages since proper logging is a rather involved problem and these packages have been written to solve them. I think the important question, why would you not use them?
Well I would always prefer tested thing and approved by community over something which still need a lot of test. Logger allows you many things which will consume you some time to implement and to test the robustness of your solution. A big plus will be the know-how of the next person who will do something with your code, in case it will be your logger, normally it would take more time to learn how its working out, since there is much more examples and documentation for java.util.logger.
Like all others mention, there are more advantages to using a more common logging system over writing your own. To be honest, the Java util logging api is not nearly as extensive and configurable as other libraries you might find out there on the internet.
Bare in mind that rolling your own always has the disadvantage of being less tested and therefore more prone to break or skip some potentially crucial messages.
Personally I prefer using SLF4J since it allows me to plug in adapters for more commonly used logging frameworks and then let's me pick my own actual logging implementation, this solves most of the problems with different library writers preferring different logging frameworks. And if you consider yourself up for the task you could writer an implementation for SLF4J yourself ;)