shell之log4jsh


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下的项目骨架,另文说明吧

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,293评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,604评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,958评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,729评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,719评论 5 366
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,630评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,000评论 3 397
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,665评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,909评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,646评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,726评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,400评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,986评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,959评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,197评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 44,996评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,481评论 2 342

推荐阅读更多精彩内容

  • 第三章 Logback 配置 我们首先介绍配置 logback 的方法,以及许多示例配置脚本。logback所依赖...
    沈林楠阅读 980评论 0 0
  • ref:https://mapr.com/support/s/article/Spark-Troubleshoot...
    clive0x阅读 908评论 0 0
  • 公司最近需要测试后台性能,所以学习使用了Jmeter,在此做记录,也分享给更多需要的人。 这篇文章是 JMeter...
    顾顾314阅读 4,246评论 0 10
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,594评论 18 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,732评论 6 342