fusesource / jansi

Jansi is a small java library that allows you to use ANSI escape sequences to format your console output which works even on windows.
http://fusesource.github.io/jansi/
Apache License 2.0
1.11k stars 140 forks source link

Remove ANSI when writing to file? #194

Closed Osiris-Team closed 3 years ago

Osiris-Team commented 3 years ago

What's the recommended way of doing this? Couldn't find a simple answer by myself... Context: I have my own custom log file writer

Osiris-Team commented 3 years ago

Found a solution (tested on jansi 2.2):

     /**
     * Returns a new {@link BufferedWriter} for the given file.
     * This writer is ANSI free, thus perfectly suitable for log files.
     * @param file File to write to.
     */
    private static BufferedWriter getBufferedWriterForFile(File file) throws Exception {
        AnsiConsole.systemInstall(); // To make sure that the console is running
        AnsiPrintStream origOut = AnsiConsole.out();
        AnsiOutputStream out = new AnsiOutputStream(
                new FileOutputStream(file),
                origOut.getMode(),
                null,
                origOut.getType(),
                origOut.getColors(),
                Charset.defaultCharset(),
                null,
                null,
                true
        );
        return new BufferedWriter(new OutputStreamWriter(out));
    }

For older versions of jansi:

     /**
     * Returns a new {@link BufferedWriter} for the given file.
     * This writer is ANSI free, thus perfectly suitable for log files.
     * @param file File to write to.
     */
    private static BufferedWriter getBufferedWriterForFile(File file) throws Exception {
        AnsiConsole.systemInstall(); // To make sure that the console is running
        AnsiOutputStream out = new AnsiOutputStream(new FileOutputStream(file));
        return new BufferedWriter(new OutputStreamWriter(out));
    }