许多时候要把错误的信息出力到linux下的系统log上面去,当然也可以自己配置logback.xml来实现。
具体的java 代码如下。
public static final String LOGGER = "logger";
public static final String LOGGER_T = "-t";
public static final String LOGGER_P = "-p";
public static final String LOGGER_USER_ERR = "user.err";
创建一个list
List<String> command = new ArrayList<>();
把需要打到linux 上面的命令都加入到command里面
command.add(Constant.LOGGER);
command.add(Constant.LOGGER_T);
command.add(logger_ID);
command.add(Constant.LOGGER_P);
command.add(Constant.LOGGER_USER_ERR);
创建进程
ProcessBuilder pb = new ProcessBuilder(command);
Process process = null;
// コマンド実行
try {
// プロセス実行
process = pb.start();
// final InputStream is1 = process.getInputStream();
// final InputStream is2 = process.getErrorStream();
// new Thread() {
// public void run() {
// BufferedReader br = new BufferedReader(
// new InputStreamReader(is1));
// try {
// String lineB = null;
//
// while ((lineB = br.readLine()) != null) {
// if (lineB != null) System.out.println(lineB);
//
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }.start();
//
// new Thread() {
// public void run() {
//
// BufferedReader br2 = new BufferedReader(
// new InputStreamReader(is2));
// try {
//
// String lineC = null;
// while ((lineC = br2.readLine()) != null) {
//
// if (lineC != null) System.out.println(lineC);
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }.start();
// 完了まで待機
process.waitFor();
if (process.exitValue() == 0) {
// 正常終了の場合
logger.info(IOUtils.toString(process.getInputStream(), StandardCharsets.UTF_8));
} else {
// 異常終了の場合
logger.error("log出力が異常に終了しました\n"
+ IOUtils.toString(process.getErrorStream(), StandardCharsets.UTF_8)
+ "\n"
+ IOUtils.toString(process.getInputStream(),
StandardCharsets.UTF_8));
}
} catch (IOException e) {
logger.error("linux logger 出力に失敗しました。", e);
} catch (InterruptedException e) {
// プロセスを強制停止
if (process != null) {
process.destroyForcibly();
}
// ユーザーよって停止
logger.error("linux logger 出力プロセスはユーザーよって停止されました。",e);
}