简体   繁体   English

如何用Java编写OS系统日志?

[英]How to write to OS system log in Java?

Mac OS has an application called Console, which contains logged messages, errors, and faults. Mac OS有一个名为Console的应用程序,它包含记录的消息,错误和错误。 I believe the Windows equivalent is Event Viewer. 我相信Windows等效的是事件查看器。 I'd imagine there is one on Linux as well, but I don't know anything about it or where it is. 我想在Linux上也有一个,但我不知道它或它在哪里。

Is it possible to get a message from Java output to a system log like this? 是否有可能从Java输出获取消息到这样的系统日志? I'm writing a GUI-based application, so there is nothing running from the command line. 我正在编写一个基于GUI的应用程序,因此命令行中没有任何内容。 The standard System.out or System.err probably won't be of much use in this case, unless I'm missing something. 在这种情况下,标准的System.outSystem.err可能没什么用,除非我遗漏了什么。

I have written a simple logging service for my application that writes to a dedicated log file, but I want to have some kind of failsafe in case an I/O error occurs while attempting to write to this file. 我为我的应用程序编写了一个简单的日志记录服务,写入专用的日志文件,但是我想在尝试写入此文件时发生I / O错误时遇到某种故障保护。

I know the IDE will display output via System.out and System.err just fine, but this is for if the end-user encounters a problem like this. 我知道IDE会通过System.outSystem.err显示输出就好了,但这是因为如果最终用户遇到这样的问题。

As an example: I've written "codeless language modules" for the application TextWrangler on the Mac. 举个例子:我为Mac上的应用程序TextWrangler编写了“无代码语言模块”。 These modules are read by TW at application startup, and if there is an error while processing them, errors get logged and can be viewed in the Mac Console application. TW在应用程序启动时读取这些模块,如果在处理它们时出错,则会记录错误并可在Mac控制台应用程序中查看。

You can redirect System.out to a log file, and Mac's Console app is the default viewer for files ending in ".log". 您可以将System.out重定向到日志文件,Mac的控制台应用程序是以“.log”结尾的文件的默认查看器。

One way this is commonly done is with a shell script that would invoke your Java program. 通常这样做的一种方法是使用一个可以调用Java程序的shell脚本。 In this Java 7 example, the output of invoking the main class MyClass is redirected to mylogfile.log. 在这个Java 7示例中,调用主类MyClass的输出被重定向到mylogfile.log。 Everything that's written with System.out will be in mylogfile.log. 使用System.out编写的所有内容都将在mylogfile.log中。

#!/bin/bash

for a in /path/to/my/jars/*
do 
CLASSPATH=$CLASSPATH:$a
done

java -Xms128M -Xmx128M -XX:MaxPermSize=128M -cp ${CLASSPATH} com.example.package.MyClass >> mylogfile.log

On Linux it is called as syslog. 在Linux上,它被称为syslog。 One of the ways that you can achieve logging to console on Mac will be to use log4j 'org.apache.log4j.net.SyslogAppender'. 在Mac上实现登录到控制台的一种方法是使用log4j'org.apache.log4j.net.SyslogAppender'。

I think this link should give you some kickstart in this direction. 我认为这个链接应该会给你这方面的一些启动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM