title: shell下记录日志log4jsh
date: 2020-08-24 15:59:19
categories:
- [学习, shell]
tags: - shell
- log4jsh
- log
介绍
{% note info %}
log4sh是shell脚本的日志框架,它的工作原理与Apache Software Foundation提供的其他优秀日志产品类似(例如log4j、log4perl)。尽管功能不如其他命令强大,但它可以简化向shell脚本添加高级日志记录的任务,并且比基本的“echo”命令强大得多。此外,还可以从.properties文件配置它,这样生产环境中的脚本就不需要更改它们生成的日志记录的数量。
<span style="color:red;">项目地址</span> <span style="color:red;">手册</span>
{% endnote %}
使用笔记
搭建环境
写本文的时候,版本是1.5.0
git clone https://github.com/kward/log4sh.git
mkdir test && cd test
cp ../log4sh/log4sh .
hello world
- 创建helloworld.sh
#! /bin/bash
## include log4jsh file
. ./log4sh
# Say Hello to the world.
logger_info "Hello, world"
# second way to Say hello
echo 'message to log' |logger_info
- 创建log4j属性文件log4sh.properties
#
# log4sh example: Hello, world properties file
#
# Set root logger level to INFO and its only appender to A1.
log4sh.rootLogger=INFO, A1
# A1 is set to be a ConsoleAppender.
log4sh.appender.A1=ConsoleAppender
# A1 uses a PatternLayout.
log4sh.appender.A1.layout=PatternLayout
log4sh.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
- 执行文件
chmod 777 *
./helloworld.sh
0 [main] INFO shell - Hello, world
0 [main] INFO shell - message to log
高级配置
可配置参数
{% tabs configtab, 1 %}
定义输出级别和输出源名称
log4sh.rootLogger=INFO, stdout
log4sh.appender.stdout=ConsoleAppender
输出INFO级别以上的log,输出源名称是stdout,stdout的输出源是ConsoleAppender
可用级别Levels
- TRACE The TRACE level has the lowest possible rank and is intended to turn on all logging.
- DEBUG The DEBUG level designates fine-grained informational events that are most useful to debug an application.
- INFO The INFO level designates informational messages that highlight the progress of the application at coarse-grained level.
- WARN The WARN level designates potentially harmful situations.
- ERROR The ERROR level designates error events that might still allow the application to continue running.
- FATAL The FATAL level designates very severe error events that will presumably lead the application to abort.
- OFF The OFF level has the highest possible rank and is intended to turn off logging.
可用的输出源Appenders
- ConsoleAppender Output sent to console (STDOUT).
- FileAppender Output sent to a file.
- DailyRollingFileAppender Output sent to a file that rolls over daily. partial; logs written, but not rotated
- RollingFileAppender Output sent to a file that rolls over by size. partial; works, but needs improvement
- SMTPAppender Output sent via email. parital; works, but needs improvement
- SyslogAppender Output sent to a remote syslog daemon. partial; only localhost supported
基本上使用ConsoleAppender或者FileAppender,其他的如果真有需要再研究
输出源可用属性
- DatePattern Configure a pattern for the output filename. no (ignored)
- File Output filename (special filename of STDERR used for logging to STDERR). yes
- MaxBackupIndex Number of old log files to keep. no (ignored)
- MaxFileSize Maximum size of old log files. no (ignored)
- Threshold Logging level of the appender. yes
只有File和Threshold表明是支持的,其他的参数会忽略
可用输出格式
- HTMLLayout Layout using HTML. no (same as SimpleLayout)
- SimpleLayout A simple default layout ('%p - %m') yes
- PatternLayout A patterned layout (default: '%d %p - %m%n') yes
HTMLLayout和SimpleLayout是一样的
输出属性Pattern Options
- c Used to output the category of logging request. As this is not applicable in shell, the conversion character will always returns 'shell'. partial (fixed)
- d Used to output the date of the logging event. The date conversion specifier may be followed by a date format specifier enclosed between braces, but this specifier will be ignored. For example, %d{HH:mm:ss,SSS}, or %d{ISODATE}. The specifier is allowed only for compatibility with log4j properties files.The default format of the date returned is equivalent to the output of the Unix date command with a format of +%Y-%m-%d %H:%M:%S. yes
- F Used to output the file name where the logging request was issued.The default value is equivalent basename $0. yes
- L This option is for compatibility with log4j properties files. no (ignored)
- m Used to output the script supplied message associated with the logging event. yes
- n This option is for compatibility with log4j properties files. no (ignored)
- p Used to output the priority of the logging event. yes
- r Used to output the number of seconds elapsed since the start of the script until the creation of the logging event. yes
- t Used to output the current executing thread. As shell doesn't actually support threads, this is simply a value that can be set that can be put into the messages.The default value is 'main'. yes
- x This option is for compatibility with log4j properties files. no (ignored)
- X Used to output the MDC (mapped diagnostic context) associated with the thread that generated the logging event. The X conversion character must be followed by an environment variable name placed between braces, as in %X{clientNumber} where clientNumber is the name of the environment variable. The value in the MDC corresponding to the environment variable will be output. yes
- % The sequence %% outputs a single percent sign.
有些属性是不支持的,直接忽略
可用的环境变量
- LOG4SH_ALTERNATIVE_NC none Provide log4sh with the absolute path to the nc (netcat) command -- e.g. /bin/nc
- LOG4SH_CONFIGURATION none Provide log4sh with the absolute path to the log4sh properties file.
- LOG4SH_CONFIG_PREFIX log4sh Define the expected prefix to use for parsing the properties file -- e.g. log4j
- LOG4SH_DEBUG none Enable internal log4sh debug output. Set to any non-empty value.
- LOG4SH_DEBUG_FILE none Define a file where all internal log4sh trace/debug/info output will be written to -- e.g. log4sh_internal.log
- LOG4SH_INFO none Enable internal log4sh info output. Set to any non-empty value.
- LOG4SH_TRACE none Enable internal log4sh trace output. Set to any non-empty value.
{% endtabs %}
定义log properties 文件
- 编写新的配置文件custom.properties
log4sh.rootLogger=DEBUG, stdout
log4sh.appender.stdout=ConsoleAppender
- 编写测试脚本
export LOG4SH_CONFIGURATION='/home/cxl/shell/test/custom.properties'
. ./log4sh
logger_info "Hello, world:${LOG4SH_CONFIGURATION}"
logger_debug "Hello, world debug"
使用文件保存
log4sh.rootLogger=DEBUG, fileout
log4sh.appender.fileout=FileAppender
log4sh.appender.fileout.File="cxl.log"
log4sh.appender.fileout.Threshold=INFO
log4sh.appender.fileout.layout=PatternLayout
log4sh.appender.fileout.layout.ConversionPattern=%c %-4r
记录日志时间
log4sh.rootLogger=DEBUG, stdout
log4sh.appender.stdout=ConsoleAppender
log4sh.appender.stdout.Threshold=INFO
log4sh.appender.stdout.layout=PatternLayout
log4sh.appender.stdout.layout.ConversionPattern=%F %d{+%Y-%m-%d %H:%M:%S} %p - %m%n
项目中封装
在真实项目中使用,我写了一篇shell下的项目骨架,另文说明吧