You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在logback.xml中添加小于(<)和大于(>)符号?

解决Logback.xml中配置Pattern包含<、>符号的问题

这个问题其实是XML解析的常见坑——因为<和>是XML的保留字符,直接写在配置里会被XML解析器误认为是标签的开始/结束,导致配置加载失败。给你两种靠谱的解决办法:

方法一:使用XML实体转义

XML规定了几个特殊字符必须转义,对于你的需求:

  • 把<替换成&lt;
  • 把>替换成&gt;

注意:不要像你之前那样写成&amp;lt;,那是把&lt;又额外转义了一次,最终输出的会是&lt;而不是你想要的<,这就错了。

修正后的完整配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<!-- Scanning for changes in configuration file and automatic re-configuration -->
<configuration scan="true" debug="true">
  <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
    <Target>System.out</Target>
    <encoder>
      <pattern>%p [%d{yyyy-MM-dd HH:mm:ss,SSS}] %c{3}:[%C{1}:%M:%L] - [%t][%file:%line] - %replace(%.-20480m){'[^A-Za-z0-9=&lt;&gt;:@\-\[\]\s!]','_'}%n</pattern>
    </encoder>
  </appender>
  <root level="INFO">
    <appender-ref ref="CONSOLE"/>
  </root>
</configuration>

方法二:使用CDATA块(更适合复杂Pattern)

如果你的Pattern里有很多特殊字符,转义起来麻烦,可以把整个Pattern内容放在<![CDATA[ ... ]]>标签内部。XML解析器会把CDATA块里的内容当作纯文本处理,不需要转义任何特殊字符,非常省心。

用这种方法的完整配置示例:

<?xml version="1.0" encoding="UTF-8"?>
<!-- Scanning for changes in configuration file and automatic re-configuration -->
<configuration scan="true" debug="true">
  <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
    <Target>System.out</Target>
    <encoder>
      <pattern><![CDATA[%p [%d{yyyy-MM-dd HH:mm:ss,SSS}] %c{3}:[%C{1}:%M:%L] - [%t][%file:%line] - %replace(%.-20480m){'[^A-Za-z0-9=<>:@\-\[\]\s!]','_'}%n]]></pattern>
    </encoder>
  </appender>
  <root level="INFO">
    <appender-ref ref="CONSOLE"/>
  </root>
</configuration>

两种方法都能解决你的问题,根据自己的习惯选就行~

内容的提问来源于stack exchange,提问作者tuk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:47:17