logback 实现给变量指定默认值
格式是 ${变量名:-默认值}
**光有冒号还不够,再加条短线后面才是默认值**
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
< appender name = "info" class = "ch.qos.logback.core.rolling.RollingFileAppender" >
< file >/logs${log.folder:-/imeth}/info.log</ file >
< rollingPolicy class = "ch.qos.logback.core.rolling.TimeBasedRollingPolicy" >
<!-- daily rollover -->
< fileNamePattern >/logs${log.folder:-/imeth}/info.%d{yyyy-MM-dd}.log</ fileNamePattern >
<!-- keep 30 days worth of history -->
< maxHistory >30</ maxHistory >
< maxFileSize >${log.file.size.max:-50}MB</ maxFileSize >
</ rollingPolicy >
< filter class = "ch.qos.logback.classic.filter.LevelFilter" >
< level >INFO</ level >
< onMatch >ACCEPT</ onMatch >
< onMismatch >DENY</ onMismatch >
</ filter >
<!-- encoders are assigned the type ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
< encoder >
< pattern >
[%d{yyyy-MM-dd HH:mm:ss}] [%thread] [%-5level] %logger{35} - %msg%n
</ pattern >
</ encoder >
</ appender >
|
logback变量
定义变量
- 在 logback.xml 中定义
- 在命令行定义
- 引入properties文件
在 logback.xml 中定义变量
1
2
3
4
5
|
<? xml version = "1.0" encoding = "UTF-8" ?>
< configuration >
< property name = "logBase" value = "/logs" />
...
</ configuration >
|
在命令行定义变量
在命令行通过大D参数来定义
1
|
java -DHOME="/home/logstore" xxx.jar
|
引入properties文件
在properties文件定义变量。logback引入properties文件后,获得变量。
通过文件路径引入properties文件:
1
2
3
4
|
< configuration >
< property file = "/AppPath/logbackVars.properties" />
...
</ configuration >
|
通过classpath引入properties文件:
1
2
3
4
|
< configuration >
< property resource = "logbackVars.properties" />
...
</ configuration >
|
properties文件的格式是 key-value 型:
1
|
HOME=/logs
|
变量的作用域
变量有三个作用域:
-
local
作用域在配置文件内有效 -
context
作用域的有效范围延伸至 logger context -
system
作用域的范围最广,整个 JVM 内都有效 -
logback
在替换变量时,首先搜索 local 变量,然后搜索 context,然后搜索 system。
如何为变量指定 scope ?
1
2
3
4
5
6
7
8
|
< configuration >
< property scope = "context" name = "home" value = "/logs" />
< appender name = "FILE" class = "ch.qos.logback.core.FileAppender" >
< file >/${home}/myApp.log</ file >
...
</ appender >
...
</ configuration >
|
变量的默认值
在引用一个变量时,如果该变量未定义,需要为其指定默认值,写法是:
${变量名:-默认值}
示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<? xml version = "1.0" encoding = "UTF-8" ?>
< configuration >
< property name = "logBase" value = "${HOME:-/logs}" />
< appender name = "file" class = "ch.qos.logback.core.rolling.RollingFileAppender" >
< rollingPolicy class = "ch.qos.logback.core.rolling.TimeBasedRollingPolicy" >
< FileNamePattern >${logBase}/log.%d{yyyy-MM-dd}.log</ FileNamePattern >
< MaxHistory >60</ MaxHistory >
</ rollingPolicy >
< encoder >
< pattern >%d{yy/MM/dd HH:mm:ss.SSS} %-5level %line %logger{15} - %msg %n</ pattern >
< charset >UTF-8</ charset >
</ encoder >
</ appender >
...
</ configuration >
|
变量使用
使用方式:
${变量名}
示例:参见前面示例中用法。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/vispin/article/details/50965669