Redirecting Printstacktrace to a file

I want to print the stack trace of an exception to a file instead of the standard output. How do I do it? Can anyone paste a small example or pseudo code?

Here's something to get you started...
import java.io.* ;
public class Logger {
    private File logFile ;
    public Logger(File logFile) throws IOException {
        this.logFile = logFile ;
        log("starting log...") ;
    public void log(String msg) throws IOException {
        synchronized (logFile) {
            PrintWriter logWriter = new PrintWriter(new FileWriter(logFile.toString(), true)) ;
            logWriter.println(msg) ;
            logWriter.flush() ;
            logWriter.close() ;
    public void log(String msg, Throwable th) throws IOException  {
        synchronized (logFile) {
            PrintWriter logWriter = new PrintWriter(new FileWriter(logFile.toString(), true)) ;
            logWriter.println(msg) ;
            th.printStackTrace(logWriter) ;      // <<---***
            logWriter.flush() ;
            logWriter.close() ;
}Throwable.printStacktrace() goes to the standard err (System.err) by default incidentally.

Similar Messages

  • Redirect standart output to file

    i want to ask how to redirect standart output to file,
    if i have statement like this System.out.println("hello"); i want hello not print in console but print to file
    thx

    Here is sample code for that:
      static{
        try {
          PrintStream obj_ps = new PrintStream(new FileOutputStream("internal.log"));
          System.setOut(obj_ps);
          System.setErr(obj_ps);
        catch (FileNotFoundException ex) {
          JOptionPane.showMessageDialog(null, "Error creating log file", "Error", JOptionPane.ERROR_MESSAGE);
      }

  • How can I redirect in a jspx file?

    Hi,
    In a jspx file I want to redirect to other jspx file if a condition is true.
    i have this source code, but it does not work on tomcat.:
    <jsp:useBean id="BeanUsuario" class="bean.BeanUsuario"
    type="bean.BeanUsuario" scope="session"/>
    <jsp:setProperty property="opcion" name="BeanUsuario"
    value="PagWebUsuarios"/>
    <c:if test="${!sessionScope.BeanUsuario.blnOk}">
    <jsp:scriptlet> response.sendRedirect("../faces/Login/login.jspx");</jsp:scriptlet>
    </c:if>
    This is the line: response.sendRedirect("../faces/Login/login.jspx");</jsp:scriptlet>.
    thanks in advance.
    Nelson Villamizar

    Redirect with the jsp:forward tag.
    http://java.sun.com/products/jsp/tags/11/syntaxref11.fm9.html

  • Redirect standard input from file to terminal

    Is there any way to redirect standard input from file to terminal within the same program? That is, get data from a file then redirect standard input to make it interactive with the terminal?

    BIJ001 wrote:
    No, the stdin, stderr, stdout, and working directory are environmental variables that are set
    when your process is launched, and they cannot be changed from within your java application.Can't they?
    //java.lang.System
    public static void setIn(InputStream in)
    //   Reassigns the "standard" input stream.
    public static void setOut(PrintStream out)
    //  Reassigns the "standard" output stream.
    public static void setErr(PrintStream err)
    //  Reassigns the "standard" error output stream.
    Since:
    JDK1.1
    Duh, you're right. I researched this looking for a way to change the working directory and found that you could not change that after launch - for some reason I remembered it wrong as being the stderr, stdin, and stdout in addition.

  • Very Basic on save printStackTrace to a file

    Hi all
    Please can someone show me how to save a printStackTrace to a file
    Thanks
    Craig

    No it is not throwing a second exceptoin in that try block
    this is the code I am using
        try {
            String[] tcmd = new String[2];
            tcmd[0] = "/craig.txt";
            tcmd[1] = commandLine;
            process = Runtime.getRuntime().exec(tcmd);
        } catch (IOException ioe) {
            JOptionPane.showMessageDialog(null,
                                          "This is from IOException...." +
                                          ioe.getMessage());
            try {
                FileWriter fw = new FileWriter("/IO_OutPut.txt");
                PrintWriter pw = new PrintWriter(fw);
                ioe.printStackTrace(pw);
            } catch (Exception io) {
                io.printStackTrace();
                JOptionPane.showMessageDialog(null,
                                              "This is from the next try block" +
                                              io.getMessage());

  • Redirect Exception Message To File

    Hello,
    I'm running an J2EE application on Tomcat.
    For the exceptions the method getMessage() is not explicit.
    And can't read the whole message of printStackTrace() on dos windows
    Now I want to code the whole message of exceptions to be redirect in a file .
    Thank you for your suggestions .

    quick and easy solution, just redirect the output of you program when you call it, e.g., do java YourClass > yourOutputFile

  • How to redirect the to the file outside the context from jsp

    Hello Everybody,
    I am trying to redirect using jsp to the file available physically in the server machine out side the application.
    How can I do it..
    Thanks
    Saikrishna

    Write a servlet which takes the file ID as parameter, reads the file from the disk and writes it to the outputstream of the response. Finally redirect to that servlet with the file ID as parameter.
    You can find here an example of such a FileServlet: [http://balusc.blogspot.com/2007/07/fileservlet.html].

  • Redirecting threaddump to a file

    Hi,
    We have the following issue.
    We are genereating thread dump using the JNI call as below
    #include <jni.h>
    #include "Test.h"
    #include <stdio.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    JNIEXPORT void JNICALL JVM_DumpAllStacks(JNIEnv *env, jclass unused);
    JNIEXPORT jstring JNICALL Java_MyThread_createThreadDump(JNIEnv *env, jclass clazz)
         jstring str = NULL;
    char* pszConsoleOutput = NULL;
    char* tmpFile = NULL;
    struct stat buf;
    int sfildes, tfildes;
    int len;
    /* Open a tmp file to record thread info */
    tmpFile = tmpnam(NULL);
    tfildes = open(tmpFile, O_CREAT|O_RDWR, 0666);
    if (unlink(tmpFile) == -1)
    return NULL;
    /* Duplicate a standard file descriptor */
    sfildes = dup(1);
    /* file descriptor 1 point to tfildes */
    dup2(tfildes, 1);
    /* Trigger thread dump */
    JVM_DumpAllStacks(env, NULL);
    /* file descriptor 1 point back to sfildes */
    dup2(sfildes, 1);
    /* Move the file pointer to the begining */
    lseek(tfildes, 0, SEEK_SET);
    /* Get the file size */
    fstat(tfildes, &buf);
    len = buf.st_size;
    /* Read the content in tmp file into output buffer */
    if (len > 0)
    pszConsoleOutput = (char *) malloc(len * sizeof(char));
    read(tfildes, pszConsoleOutput, len);
    pszConsoleOutput[len] = '\0';
    /* Display the thread output in Java Console */
    if (pszConsoleOutput != NULL)
    str = (*env)->NewStringUTF(env, pszConsoleOutput);
    /* Release memory */
    free(pszConsoleOutput);
    return str;
    we are trying to capture it in a temp file, but the dump vanishes.
    Can anyone help us in capturing the thread dump generated at the console.

    Here's something to get you started...
    import java.io.* ;
    public class Logger {
        private File logFile ;
        public Logger(File logFile) throws IOException {
            this.logFile = logFile ;
            log("starting log...") ;
        public void log(String msg) throws IOException {
            synchronized (logFile) {
                PrintWriter logWriter = new PrintWriter(new FileWriter(logFile.toString(), true)) ;
                logWriter.println(msg) ;
                logWriter.flush() ;
                logWriter.close() ;
        public void log(String msg, Throwable th) throws IOException  {
            synchronized (logFile) {
                PrintWriter logWriter = new PrintWriter(new FileWriter(logFile.toString(), true)) ;
                logWriter.println(msg) ;
                th.printStackTrace(logWriter) ;      // <<---***
                logWriter.flush() ;
                logWriter.close() ;
    }Throwable.printStacktrace() goes to the standard err (System.err) by default incidentally.

  • LrHttp.get redirect and downloading a file "zip"

    I trying to figure if I can use LrHttp.get to download a zip file via a URL that does a redirection can anyone help?

    This is the entire file, executed when user selects plugin extra from file menu:
    local function httpRedirTest( call )
        local body, headers = LrHttp.get( "http://www.robcole.com/_test/redir2zip.cfm" )
        fso:writeFile( "C:\\_temp\\nada_.zip", body )
    end
    app:call( Service:new{ name="Test", async=true, guard=App.guardVocal, main=function( call )
        httpRedirTest( call )
    end } )
    Note: app-call-service-new... is a glorified call to LrFunctionContext.postAsyncTaskWithContext.
    i.e. it must be called from an asynchronous task.
    What is or is not happening when you execute similar code?
    Could the problem be due to internet configuration (i.e. can your browser download the zip file when you click on the link above?).
    Can you download zips when not through redirection?
    i.e. if you replaced the url above with:
    http://www.robcole.com/_test/nada.zip
    does it work?
    Rob

  • Sorry server redirect to simple html file hosted on ACE

    I know this question has already been asked and all I'm doing here is to double check to see that the status of this feature is still unsupported??
    Is this correct?
    regards
    Tyrone

    No. You can only forward client requests to a rserver which can host your file, or send a 301/302 redirect to a maintenance URL

  • Redirected AppData and Bookmark file.

    Hi
    We are using Firefox and Windows 7/8 redirected folders.
    We are experiencing some sync issues regarding the bookmark file not being sync because of the file being lock on use.
    The sync for the offline folders is set to happen every 30 minutes in the background but if the user never close Firefox, the file will never be synced. And this problem resolve in user not able to access their bookmarks.
    Is there anyone using the redirected folder that could give me an hint on how to correct that problem.
    We are using Firefox ESR 10.0.0.6, Windows 7 SP1 Enterprise in a Windows 2008 R2 AD.
    Redirected folders are being used, all user profile folders are redirected on the network.
    Thank you!
    Mathieu

    That is done purposely to avoid fragmentation of the file from slowing down access. All SQLite database files have a default file size and are increased in chunks of that same size. For places.sqlite that is 10 MB.
    * [https://bugzilla.mozilla.org/show_bug.cgi?id=581606 Bug 581606] - Avoid sqlite fragmentation via SQLITE_FCNTL_CHUNK_SIZE

  • How to redirect console to a file?

    I'm running WLS811 on RH9 and have it starting automatically via init.d with
    the following line
    daemon ./startWebLogic.sh &
    Everything is going great, except the console is logged to the
    /var/log/boot.log file, along with all the other server stuff. Can I
    redirect the console to a file inside of my domain instead?
    I tried putting a <Log Filename="server.log"/> in my config.xml but that
    only put the server startup stuff in there, not the
    System.err.println("something here"); stuff.
    Any suggestions? Much appreciated, thanks.

    Try this,
    edit your startWeblogic.cmd and in the almost final line, the one that starts
    weblogic:
    "%JAVA_HOME%\bin\java -hotspot ...."
    add this at the end of that line:
    " 1>exit1.txt 2>exit2.txt"
    and restart weblogic. It should create at least exit1.txt with everything that
    appears in the console, including errors.
    Hope this helps
    dn <[email protected]> wrote:
    Hey Flip
    I was searching the forum for this and ended up on this thread.
    YOu did this on UNix right .
    Any idea how to make it work in Windows
    I tried startweblogic > log.txt , but the System.err or System.out is
    still coming up in the command console
    TIA
    Flip wrote:
    Howdy. With the help of a guru, I was able to get it to work. I tookout
    the 'daemon' commnd and put '>> ./server.log' before the & and allis good
    now. Thanks.
    "Flip" <[remove][email protected]> wrote in message
    news:3fc6241b$[email protected]..
    I'm running WLS811 on RH9 and have it starting automatically via init.dwith
    the following line
    daemon ./startWebLogic.sh &
    Everything is going great, except the console is logged to the
    /var/log/boot.log file, along with all the other server stuff. Can
    I
    redirect the console to a file inside of my domain instead?
    I tried putting a <Log Filename="server.log"/> in my config.xml butthat
    only put the server startup stuff in there, not the
    System.err.println("something here"); stuff.
    Any suggestions? Much appreciated, thanks.

  • Printing exceptions (printStackTrace()) in a file

    Dear everyone,
    I need to print the exceptions' stack traces in a file
    (e.printStackTrace()).
    How do I do that?
    I attempted by setting the out stream (System.setOut())
    to my file's print stream. But it didn't work.
    Thanks a bunch for your help!
    George

    Simple :
      try {
        //code
      } catch (Throwable t) {
        PrintWriter writer = new PrintWriter(new FileWriter("c:\\temp\\error.txt"));
        t.printStackTrace(writer);
        writer.flush();
        writer.close();
      }

  • [JSF] redirect to a PDF or XLS file.

    How to make redirection to some new file?
    Could you make that example in JSF?
    I can't find where i can make a PAGE there...
    For example I want to make excel file with help of POI and make an output to the screen. With the help of EventResult I made this on UIX, but not JSF...
    Thanks in Advance.

    for PDF, try this out...
    http://www.apple.com/downloads/dashboard/status/dashclipping.html
    allows you to use a URL to display in a window. nice widget. I use it to check a site or two, but i have tested on local PDF files, and it works fine...
    eg:
    URL = file://localhost/Users/usernamehere/Desktop/example.pdf
    Beavis2084

  • File getting locked in RDC when saving it to redirected drive (from remoteapp).

    Hello,
    when exporting excel file from our RemoteApp to my local C disk (\\tslcient\c) the file is getting locked and can not be used until I close the RemoteApp. If for example I try to delete file before closing RemoteApp,
    I get the error that file is being used by Remote Desktop Client.
    If during export I choose to save the file on remoteApp server, or on mapped network drive, it is not getting locked and can be used right away.
    Is there a way to save it to my redirected C drive and be able to use it without closing remoteApp ?

    Hi,
    Thank you for posting in Windows Server Forum.
    Initially see that you have client mapped drive is enabled. You can enable the setting under collection properties client settings-Drive Redirection Option. In addition, we can also check the GPO setting “Do not allow drive redirection” under below
    mention path.
    Computer Configuration\Policies\Administrative Templates\Windows Components\Remote Desktop Services\Remote Desktop Session Host\Device and Resource Redirection
    Also can generate some script that would add shortcut and points to the shared drive. After this the shortcut would be added to the default location you see when you do the save file from your application.    
    Hope it helps!
    Thanks.
    Dharmesh Solanki
    Client drive is redirecting without problem and it is accessible, we can browse it, copy and save files there.
    The problem is that when we save file from RemoteApp to redirected client drive, the file is locked by remote desktop connection process and can not be accessed until RemoteApp is closed.

Maybe you are looking for

  • Deploying QPM policies through CLI

    Hello, We are using QPM v4.1 Combined (provisioning + monitoring) and using the IP Telephony wizard to create Voice policies on the network. Deploying polices directly from QPM showed up that some deployment jobs fail for reasons such as "QPM interna

  • Yearly recurring meeting created on iPhone breakes iCal sync with exchange

    I encounter a reproducable bug with Snow Leopard 10.6.1's iCal stopping sync with Exchange 2007 SP1 (Update Rollup 7), as soon a i create a yearly recurring meeting on iPhone 3GS connected to same Exchange Server via Active Sync. After creating this

  • Possible to mount off the external antenna of the MSI AP11B?

    Hi! I am thinking of buying the MSI AP11B Acces Point. But is it possible to mount of the external antenna, and mount another antenna to boost up the signal? Best Regards  

  • I am trying to update my apple tv, but it always returns an error

    i am trying to update my apple tv, but it always returns an error that says it can't be done right now, try again later. I had to change my DNS on my iphone and ipad, and those then upgraded fine, just not apple tv. Any help will be appreciated.

  • App manager won't install

    Running Mac OS 10.6.8 - downloaded the Adobe Applications Manager to get a Cloud  App download, and the dmg install package opens- but clicking to run the install part of the process, on the unbundled file, isn't successful. The program runs, asks fo