Hi guys,
I want to write log files (.txt) to keep trace of what happens in my game server. But I don’t know how this effectively works. If I am correct the server will write the file real time while it is also elaborating client requests like movement etc Isn’t this going to make server performace worse?
Can you please tell me the right approach or suggest me any library or similar utility?
Well, standalone Java 1.8 has the java.io package, that you could use. It’s got goodies such as PrintWriter, ObjectOutputStream, and ObjectInputStream, among others. The API documentation is here:
http://docs.oracle.com/javase/7/docs/api/java/io/package-summary.html
I know them but are they optimized to avoid worse performance?
They’re in the standard library. There’s your answer.
Tip: don’t optimize until you need to.
Use a logging library which allows to enable logging as needed.
Probably the best idea
If you just want very simple functionality, then you can just call this at the start of your program,
try
{
PrintStream out = new PrintStream("path to log here.txt");
System.setOut(out);
System.setErr(out);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
Anytime you then print out with System.out.println() or System.err.println(), then it will write a line to the log.
Uh seems very good, I like your solution, gonna try in the code. Thanks a lot
java -jar myjar.jar > output.txt
Will redirect the output too.
I guess since you are talking about a server this is possibly.
[quote=“BurntPizza”]
You need [icode]java -jar myjar.jar > output.txt 2>&1[/icode] if you want both stdout and stderr. Assuming Windows, of course.
It’s a bad idea to reinvent the wheel. There are already really good and fast logging libraries. As with every library it will take you some (concerning logging libraries not much) time to get the hang of it, but it will serve you well in the future.
I personally can recommend SLF4J combined with Log4j.
Slf4j is a very fast logging wrapper. Usually (e.g. with log4j alone) you would log a debug line with a variable like:
log.debug("speed: " + speed);
Everytime this method gets executed, even if we have set the logging level above debug (and that’s the crucial point), a string concatenation takes place. With slf4j you print logging messages this way:
log.debug("speed: {}", speed);
Only if we really want the debug messages logged, we have to perform a string replacement.
You can try chronicles, the fastest way writing logs to disk https://github.com/peter-lawrey/Java-Chronicle