net.core 的 log4net 配置文件和 UDP 动态追加远程端口
log4net config file for net.core with UDP Append remote port dynamically
我有一个 log4net.config 文件,我希望能够通过 Program.cs 文件在其中动态注入 RemotePort 变量。但我收到以下错误:
System.FormatException: Input string was not in a correct format.
我能够使用此策略动态传递 RemoteAddress :
log4net文件中的代码
<appender name="UdpAppender" type="log4net.Appender.UdpAppender">
<RemoteAddress value="%property{RemoteAddress}" />
<RemotePort value="%property{RemotePort}" />
<encoding value="utf-8"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level - %property{log4net:HostName} - %message%newline" />
</layout>
</appender>
代码在Program.cs
log4net.GlobalContext.Properties["RemotePort"] = 514;
参考文章中所示的相同概念也适用于此处。
您需要将 PatternString
转换为 Int32
,这需要实现 IConvertFrom
的自定义类型转换器。
重用 PatternString
的实现 %property{RemotePort}
将替换为通过 log4net.GlobalContext.Properties["RemotePort"] = 514
传入的值,这将导致 514
.
public class NumericConverter : IConvertFrom
{
public NumericConverter()
{}
public Boolean CanConvertFrom(Type sourceType)
{
return typeof(String) == sourceType;
}
public Object ConvertFrom(Object source)
{
String pattern = (String)source;
PatternString patternString = new PatternString(pattern);
String value = patternString.Format();
return Int32.Parse(value);
}
}
在启动时注册此类型转换器,如下所示
log4net.Util.TypeConverters.ConverterRegistry.AddConverter(typeof(int), new NumericConverter());
我有一个 log4net.config 文件,我希望能够通过 Program.cs 文件在其中动态注入 RemotePort 变量。但我收到以下错误:
System.FormatException: Input string was not in a correct format.
我能够使用此策略动态传递 RemoteAddress :
log4net文件中的代码
<appender name="UdpAppender" type="log4net.Appender.UdpAppender">
<RemoteAddress value="%property{RemoteAddress}" />
<RemotePort value="%property{RemotePort}" />
<encoding value="utf-8"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level - %property{log4net:HostName} - %message%newline" />
</layout>
</appender>
代码在Program.cs
log4net.GlobalContext.Properties["RemotePort"] = 514;
参考文章中所示的相同概念也适用于此处。
您需要将 PatternString
转换为 Int32
,这需要实现 IConvertFrom
的自定义类型转换器。
重用 PatternString
的实现 %property{RemotePort}
将替换为通过 log4net.GlobalContext.Properties["RemotePort"] = 514
传入的值,这将导致 514
.
public class NumericConverter : IConvertFrom
{
public NumericConverter()
{}
public Boolean CanConvertFrom(Type sourceType)
{
return typeof(String) == sourceType;
}
public Object ConvertFrom(Object source)
{
String pattern = (String)source;
PatternString patternString = new PatternString(pattern);
String value = patternString.Format();
return Int32.Parse(value);
}
}
在启动时注册此类型转换器,如下所示
log4net.Util.TypeConverters.ConverterRegistry.AddConverter(typeof(int), new NumericConverter());