/*
 * Copyright (C) 2004 TiongHiang Lee
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not,  write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Email: thlee@onemindsoft.org
 */

package org.onemind.commons.java.util;

import java.io.*;
import java.io.File;
import java.io.FileInputStream;
import java.util.logging.LogManager;
/**
 * Utility methods for loggin
 * @author TiongHiang Lee (thlee@onemindsoft.org)
 * @version $Id: LogUtils.java,v 1.4 2005/08/08 05:21:51 thlee Exp $ $Name:  $
 */
public final class LogUtils
{

    /**
     * {@inheritDoc}
     */
    private LogUtils()
    {
    }

    /**
     * Init java logging by looking for logging.properties in the class paths
     */
    public static void initLoggingFromClassPath()
    {
        String classPath = (String) System.getProperties().get("java.class.path");
        String[] paths = null;
        if (classPath.indexOf(";") != -1)
        { //must be windows
            paths = classPath.split(";");
        } else
        {
            paths = classPath.split(":");
        }
        for (int i = 0; i < paths.length; i++)
        {
            if (!paths[i].endsWith(".jar"))
            {
                String config = FileUtils.concatFilePath(paths[i], "logging.properties");
                if (new File(config).exists())
                {
                    //System.out.println("Use logging configuration " + config);
                    try
                    {
                        LogManager.getLogManager().readConfiguration(new FileInputStream(config));
                    } catch (Exception e)
                    {
                        //nothing it can do
                        //System.out.println("- init logging problem: " + e.getMessage());
                    }
                }
            }
        }
    }

    /**
     * Get the stack trace in a string
     * @param e the exception
     * @return the stack trace string
     */
    public static String getTrace(Throwable e)
    {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(buffer);
        e.printStackTrace(ps);
        ps.flush();
        return new String(buffer.toByteArray());
    }
}