I have a log4net.config file in which I want to be able to inject the RemotePort variable dynamically via Program.cs file. But I am getting the following error :
System.FormatException: Input string was not in a correct format.
I was able to pass RemoteAddress dynamically with this strategy :
log4net config file for net.core with UDP Append remote address dynamically
The code in the log4net file
<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>
The code in Program.cs
log4net.GlobalContext.Properties["RemotePort"] = 514;
The same concept as shown in the referenced article is also applicable here.
You need a translation from a PatternString
to an Int32
which requires a custom type converter implementing IConvertFrom
.
Reusing the implementation of a PatternString
the %property{RemotePort}
will be replaced by the value passed in via log4net.GlobalContext.Properties["RemotePort"] = 514
, which will result into 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);
}
}
Register this type converter at startup as shown below
log4net.Util.TypeConverters.ConverterRegistry.AddConverter(typeof(int), new NumericConverter());