Java stderr to file

Java stderr to file

In java the three main Streams stdin (standard input) , stdout (standard output) and stderr (standard output error) are handled by default by System.in, Sytem.out and System.err respectively. Sometimes we may need to change the output according to our needs, this can be done in many ways such us using the OS to tell what stream we need to use or using java to set what streams we want to be used.

In these examples is shown how to deal with these streams in different sceenarios.

Redirecting streams to file from console in Unix

java MyExample > output.log 2>error.log

Redirecting Output Streams to Files

This example redirects both output streams to 2 different files. It produces an ArithmeticException dividing by 0 and the error trace will be stored in the stderr.log. The results won’t be shown in the console.

import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; public class OutPuts < public static void main(String[] args) < try < FileOutputStream fout = new FileOutputStream("stdout.log"); FileOutputStream ferr = new FileOutputStream("stderr.log"); PrintStream out = new PrintStream(fout); PrintStream err = new PrintStream(ferr); System.setOut(out); System.setErr(err); out.println("trace console 1"); >catch (FileNotFoundException ex) < ex.printStackTrace(); >System.out.println("trace console 2"); System.out.println(100/0); > >

Redirecting Output Error Stream to the Standard Out Stream.

Redirecting Output Streams to Files and Printing the result in the console.

In this example a «proxy» class I used, so that every time the print or println methods are called its output will be printed by the console and also stored the specified files.

import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; public class OutPuts < public static void main(String[] args) < System.setOut(new ProxyPrintStream(System.out, "stdout.log")); System.setErr(new ProxyPrintStream(System.err, "stderr.log")); System.out.println("trace console 1"); System.out.println(100 / 0); >> class ProxyPrintStream extends PrintStream < private PrintStream fileStream = null; private PrintStream originalPrintStream = null; public ProxyPrintStream(PrintStream out, String FilePath) < super(out); originalPrintStream = out; try < FileOutputStream fout = new FileOutputStream(FilePath,true); fileStream = new PrintStream(fout); >catch (FileNotFoundException e) < e.printStackTrace(); >> public void print(final String str) < originalPrintStream.print(str); fileStream.print(str); >public void println(final String str) < originalPrintStream.println(str); fileStream.println(str); >>

* This example appends traces to the existing file change new FileOutputStream(FilePath,true) for new FileOutputStream(FilePath) to create a new file each time.

Читайте также:  Menu and submenu in html css

Redirecting Output Streams in Log4J

This example prints all the traces ment for the standard outputs to the LOG4J files, so you can make sure that all traces are there.

/** * To change tie the sysOut and sysErr to the log */ public static void tieSystemOutAndErrToLog() < System.setOut(createLoggingProxy(System.out)); System.setErr(createLoggingProxy(System.err)); >public static PrintStream createLoggingProxy(final PrintStream realPrintStream) < return new PrintStream(realPrintStream) < public void print(final String string) < logger.warn(string); >public void println(final String string) < logger.warn(string); >>; >

Источник

How do I redirect only stderr?

I am having a bit of trouble doing this. I am required to run a compiled .java file and redirect only stderr to a file called error. So the .java file is named javaProgram.java. This is what I have tried:

it appears that there is stuff in there, even when I know for a fact that the specific .java file has no errors. Am I doing something wrong? All I want this error file to display is errors, not anything else.

2 Answers 2

Your first try was correct; 2>filename is how you redirect stderr. It may be the case that your program is writing some non-errors to stderr, or the java program is running other programs that output to stderr.

The simple answer is that it isn’t possible. Standard error is used for writing diagnostic output and it’s up to the applications to define what is diagnostic/error output. That’s according to the POSIX standard.

If you are going to cite the POSIX spec, please cite a specific section and not the entire document. It’s huge.

Since when is it not possible to redirect stderr to file in POSIX? You’ll have to provide an actual quote for that.

@l0b0 that isn’t what Jeight is saying. It’s up to applications to decide what goes to STDOUT and what goes to STDERR; it would be entirely possible to shove everything into STDOUT, for example, and then redirecting STDERR would have no effect. Or, as in this case, it’s possible (and standard practice) to put some things that aren’t strictly errors into STDERR. The only way it would be possible to parse the errors from other diagnostics would be if the errors are marked with ‘ERROR:’ or something. There may be a verbosity switch that could help, but that’s program-specific.

OP posed two semantically different problems: «redirect only stderr to a file called error» and «I want this error file to display is errors, not anything else.» The first part of that certainly isn’t impossible, is my point.

@l0b0 You’ve got it backwards. The OP definitely can redirect the stderr to a file called error. He can not choose what Java outputs as stderr because the content of stderr is controlled by the application and not the user. What he can do is grep the file that stderr was passed to for actual error messages.

Источник

Java – How to use Log4j to write/capture stdout and stderr to a file and using Windows and Tomcat 5.5 (Java)

I am using Windows 2008 R2 and Apache Tomcat 5.5, for your information.

STDOUT and STDERR can be automatically logged through Apache Tomcat properties, via Logging tab -> Redirect Stdout and Redirect Stderror textboxes.

But I want to control this through log4j.

I’m trying to leverage ConsoleAppender and the TimeAndSizeRollingAppender class to rollover what would normally be controlled by Apache Tomcat’s innate logging.

Basically, however Tomcat redirects stdout and stderr to a file, I want to do the same thing using log4j and the log4j.properties file.

  1. How do I compile any of these classes? What should be the classpath? I tried compiling the class from the sysgears link but it returned 7 errors such as unable to find symbol Class Logger and symbol Class OutputStream.
  2. After compiling, specifically from the sysgears link, how can I use the class? It states to use the class, just write: System.setErr(new PrintStream(new LoggingOutputStream(
    System.err, Logger.getLogger(«outLog»), Level.ERROR)));

Great, but where do I write it? In a separate file? Tomcat Properties?

I would appreciate any help.

Thank you very much for your time.

Here is my full log4j.properties file:

log4j.rootLogger=INFO, CATALINA, LOCALHOST, MANAGER, HOST-MANAGER, ADMIN, CONSOLE # Define all the appenders log4j.appender.CATALINA=org.apache.log4j.appender.TimeAndSizeRollingAppender log4j.appender.CATALINA.file=D:/Program Files (x86)/Apache Software Foundation/Tomcat- 5.5.28/logs/catalina.log log4j.appender.CATALINA.Threshold=DEBUG log4j.appender.CATALINA.DatePattern='.'yyyy-MM-dd-HH-mm log4j.appender.CATALINA.layout=org.apache.log4j.PatternLayout log4j.appender.CATALINA.MaxFileSize=20KB log4j.appender.CATALINA.DateRollEnforced=true log4j.appender.CATALINA.MaxRollFileCount=100 log4j.appender.CATALINA.ScavengeInterval=-1 log4j.appender.CATALINA.BufferedIO=false log4j.appender.CATALINA.CompressionAlgorithm=ZIP log4j.appender.CATALINA.layout.conversionPattern = %-5p %-23d [%t] %x: %c - %m%n log4j.appender.LOCALHOST=org.apache.log4j.appender.TimeAndSizeRollingAppender log4j.appender.LOCALHOST.file=D:/Program Files (x86)/Apache Software Foundation/Tomcat-5.5.28/logs/localhost.log log4j.appender.LOCALHOST.Threshold=DEBUG log4j.appender.LOCALHOST.DatePattern='.'yyyy-MM-dd-HH-mm log4j.appender.LOCALHOST.layout=org.apache.log4j.PatternLayout log4j.appender.LOCALHOST.MaxFileSize=20KB log4j.appender.LOCALHOST.DateRollEnforced=true log4j.appender.LOCALHOST.MaxRollFileCount=100 log4j.appender.LOCALHOST.ScavengeInterval=-1 log4j.appender.LOCALHOST.BufferedIO=false log4j.appender.LOCALHOST.CompressionAlgorithm=ZIP log4j.appender.LOCALHOST.layout.conversionPattern = %-5p %-23d [%t] %x: %c - %m%n log4j.appender.MANAGER=org.apache.log4j.appender.TimeAndSizeRollingAppender log4j.appender.MANAGER.file=D:/Program Files (x86)/Apache Software Foundation/Tomcat-5.5.28/logs/manager.log log4j.appender.MANAGER.Threshold=DEBUG log4j.appender.MANAGER.DatePattern='.'yyyy-MM-dd-HH-mm log4j.appender.MANAGER.layout=org.apache.log4j.PatternLayout log4j.appender.MANAGER.MaxFileSize=20KB log4j.appender.MANAGER.DateRollEnforced=true log4j.appender.MANAGER.MaxRollFileCount=100 log4j.appender.MANAGER.ScavengeInterval=-1 log4j.appender.MANAGER.BufferedIO=false log4j.appender.MANAGER.CompressionAlgorithm=ZIP log4j.appender.MANAGER.layout.conversionPattern = %-5p %-23d [%t] %x: %c - %m%n log4j.appender.HOST-MANAGER=org.apache.log4j.appender.TimeAndSizeRollingAppender log4j.appender.HOST-MANAGER.file=D:/Program Files (x86)/Apache Software Foundation/Tomcat-5.5.28/logs/host-manager.log log4j.appender.HOST-MANAGER.Threshold=DEBUG log4j.appender.HOST-MANAGER.DatePattern='.'yyyy-MM-dd-HH-mm log4j.appender.HOST-MANAGER.layout=org.apache.log4j.PatternLayout log4j.appender.HOST-MANAGER.MaxFileSize=20KB log4j.appender.HOST-MANAGER.DateRollEnforced=true log4j.appender.HOST-MANAGER.MaxRollFileCount=100 log4j.appender.HOST-MANAGER.ScavengeInterval=-1 log4j.appender.HOST-MANAGER.BufferedIO=false log4j.appender.HOST-MANAGER.CompressionAlgorithm=ZIP log4j.appender.HOST-MANAGER.layout.conversionPattern = %-5p %-23d [%t] %x: %c - %m%n log4j.appender.ADMIN=org.apache.log4j.appender.TimeAndSizeRollingAppender log4j.appender.ADMIN.file=D:/Program Files (x86)/Apache Software Foundation/Tomcat-5.5.28/logs/admin.log log4j.appender.ADMIN.Threshold=DEBUG log4j.appender.ADMIN.DatePattern='.'yyyy-MM-dd-HH-mm log4j.appender.ADMIN.layout=org.apache.log4j.PatternLayout log4j.appender.ADMIN.MaxFileSize=20KB log4j.appender.ADMIN.DateRollEnforced=true log4j.appender.ADMIN.MaxRollFileCount=100 log4j.appender.ADMIN.ScavengeInterval=-1 log4j.appender.ADMIN.BufferedIO=false log4j.appender.ADMIN.CompressionAlgorithm=ZIP log4j.appender.ADMIN.layout.conversionPattern = %-5p %-23d [%t] %x: %c - %m%n # Configure which loggers log to which appenders log4j.logger.org.apache.catalina.core.ContainerBase.[Catalina].[localhost]=INFO, LOCALHOST log4j.logger.org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/manager]=\ INFO, MANAGER log4j.logger.org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/host-manager]=\ INFO, HOST-MANAGER log4j.logger.org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/admin]=\ INFO, ADMIN 

Best Solution

1) How do I compile any of these classes? What should be the classpath? I tried compiling the class from the sysgears link but it returned 7 errors such as unable to find symbol Class Logger and symbol Class OutputStream.

You need to have the log4j jar on your classpath, and import the correct classes at the top of your file. Something like,

import java.io.PrintStream; import java.io.OutputStream; import org.apache.log4j.Logger; 

Источник

Оцените статью