Default values for AdoNetAppender parameter

空扰寡人 提交于 2019-12-21 09:22:27

问题


I am using log4net with AdoNetAppender. It logs all log info into a table. This table actually has 2 Integer columns (can be null).

Here is the relevant part of my log4net config:

<commandText value="INSERT INTO ActivityLog ([Date],[Thread],[Level],[Logger],[Message],[DealID]) 
                 VALUES (@log_date,@thread,@log_level,@logger,@message,@DealID)" />

 //other parameters hten DealID
<parameter>
      <parameterName value="@DealID" />
      <dbType value="Int32" />
       <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%property{DealID}" />
      </layout>
    </parameter>

What I found out was if I don't explicitly set using something like log4net.ThreadContext.Properties["DealID"] = DealID; it throws me an exception:

System.FormatException occurred
  Message="Failed to convert parameter value from a String to a Int32."
  Source="System.Data"
  StackTrace:
       at System.Data.SqlClient.SqlParameter.CoerceValue(Object value, MetaType destinationType)
  InnerException: System.FormatException
       Message="Input string was not in a correct format."
       Source="mscorlib"
       StackTrace:
            at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
            at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
            at System.String.System.IConvertible.ToInt32(IFormatProvider provider)
            at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
            at System.Data.SqlClient.SqlParameter.CoerceValue(Object value, MetaType destinationType)
       InnerException: 

I would have to set it like:

log4net.ThreadContext.Properties["DealID"] = 0;

Is there anyway that I can set a default parameter value in my log4net config for this Int32 field so that I don't need to set it explicitly to 0 if no value is supplied? And it makes me wonder why it does not happen to fields which are set as varchar (though no value is supplied to them).


回答1:


Change your appender:

<parameter>
    <parameterName value="@DealID" />
    <dbType value="Int32" />
    <layout type="log4net.Layout.RawPropertyLayout">  <!-- notice this -->
        <key value="DealID" />  <!-- and notice this instead of the pattern layout -->
    </layout>
</parameter>

And to give credit, I found it from this thread. (And a bunch of other searching trying to do the same thing.



来源:https://stackoverflow.com/questions/1954159/default-values-for-adonetappender-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!