为什么日志消息不能在文本文件中?

时间:2012-10-25 13:42:49

标签: java logging

我使用了一个初始化logger和参数的函数。 虽然我在控制台中调用了这个函数LogMsg和newline,但它在文本文件中给出了一行。为什么会这样?

String logmsg="Line1\n"+"Line2\n";

public static void LogMsg(Logger logger,String pathname,Level level,String logmsg){
    //logger=Logger.getLogger("LogMsg");
    FileHandler fh=null;
    try {
        fh = new FileHandler(pathname,300000,1,true);
        fh.setFormatter(new SimpleFormatter());
         LogRecord record1 = new LogRecord(level, logmsg);
         logger.addHandler(fh);
            logger.log(record1);
            fh.close();

    } catch (SecurityException e) {
        // TODO Auto-generated catch block

        //e.printStackTrace();
        System.out.println("Failed to log message due to lack of permissions.");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        //e.printStackTrace();

        System.out.println("Failed to log message");
    }


}

1 个答案:

答案 0 :(得分:2)

尝试

String logmsg="Line1\r\n"+"Line2\r\n";

或更好

logmsg = String.Concat("Line1",Environment.NewLine,"Line2",Environment.NewLine);

或者更好的是仍然使用类似

的StringBuilder
logmsg = CreateLogMessage(new string [] {"Line1", "Line2"});

public static CreateLogMessage(string[] argLines);
{
  StringBuilder sb = new StringBuilder(argLines.Length);
  foreach(String line in argLines)
  {
    sb.AppendLine(line);
  }
  return sb.ToString();
}

Environment.Newline将根据预期的行尾令牌来处理os差异。