【发布时间】:2019-10-25 19:40:38
【问题描述】:
每当我的数据出现问题时,我都会尝试使用 Log4Net 的 Rolling File Appender 创建日志文件。因为我使用变音符号和非拉丁字符,所以我希望文件编码为 UTF-8。
通常,如果文件没有任何变音符号/非拉丁字符,则将其编码为 ASCII。如果它确实记录了变音符号/非拉丁字符,它会自动将其编码为 UTF-8。我希望它始终使用 UTF-8。
我的第一个解决方案是使用<encoding value="utf-8"/>。这给了我带有 BOM 的 UTF-8,这是我不想要的。所以this Stackoverflow 解决方案告诉我使用<encoding type="System.Text.UTF8Encoding"/>。我试过了,我会得到这个错误:
log4net:ERROR Failed to find type [System.Text.UTF8Encoding]
System.TypeLoadException: Could not load type 'System.Text.UTF8Encoding' from assembly 'log4net, Version=2.0.8.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a'.
at System.Reflection.RuntimeAssembly.GetType(RuntimeAssembly assembly, String name, Boolean throwOnError, Boolean ignoreCase, ObjectHandleOnStack type, ObjectHandleOnStack keepAlive)
at System.Reflection.RuntimeAssembly.GetType(String name, Boolean throwOnError, Boolean ignoreCase)
at log4net.Repository.Hierarchy.XmlHierarchyConfigurator.CreateObjectFromXml(XmlElement element, Type defaultTargetType, Type typeConstraint)
log4net:ERROR Failed to create object to set param: encoding
我尝试在 Apache 的 Jira 上进行挖掘,发现了这个 post,它还告诉我使用 <encoding type="System.Text.UTF8Encoding"/>,这与 Stackoverflow 解决方案相同。
然后我假设可能是因为我使用的是 .NET Core 2.2,我不得不尝试不同的类型。我也尝试了<encoding type="System.Text.Encoding.UTF8"/>、<encoding type="UTF8Encoding"/>、<encoding type="Encoding.UTF8"/>,但这些都不起作用。
这是我的 XML 的 appender 部分:
<appender name="file" type="log4net.Appender.RollingFileAppender">
<threshold value="WARN" />
<file type="log4net.Util.PatternString" value="%property{LogName}" />
<appendToFile value="true" />
<!--<encoding value="utf-8"/>-->
<encoding type="System.Text.UTF8Encoding"/>
<rollingStyle value="Size" />
<maximumFileSize value="1GB" />
<staticLogFileName value="false" />
</appender>
我需要做其他设置吗?
【问题讨论】:
-
考虑到作为 ascii 一部分的字符具有相同的编码,“在 ascii 中直到有一个非 ascii 字符,然后转换为 utf-8”和“始终在 utf-8”之间有什么区别在 ascii 和 utf-8 中?
-
到目前为止,据我所知,一旦文件具有非拉丁字符(例如具有变音符号或外语(韩语、日语等)),它就会被编码为 UTF-8。我正在尝试制作另一个脚本,该脚本必须在执行某些操作之前检测文件编码,但此时我可能只有一个脚本可以检测两者
-
我的意思是,ASCII 是完全有效的 UTF-8。如果您有一个以 ASCII 编码的文件,则可以使用 UTF-8 对其进行解码,因为 ASCII 是 UTF-8 的子集。任何检测文件是否为 UTF-8 的脚本也会将 ASCII 检测为有效的 UTF-8。