我正在尝试添加一个自定义属性,这是一个guid,但它给了我这个错误:

  

System.InvalidCastException:失败   从String转换参数值   一个Guid。 --->   System.InvalidCastException:无效   从'System.String'转换为   '的System.Guid'。

我在配置中指定了这个:

<parameter>
<parameterName value="@id" />
<dbType value="Guid" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%X{id}" />
</layout>
</parameter>

我使用的实际代码(片段)是:

        Guid guid = Guid.NewGuid();
        if (defaultLogger.IsEnabledFor(level))
        {
            var loggingEvent = new LoggingEvent(ThisDeclaringType,
 defaultLogger.Repository, defaultLogger.Name, level, message, exception);
            loggingEvent.Properties["Id"] = guid;

请帮忙吗? :)数据库中的id字段被定义为唯一标识符NOT NULL,但它没有主键约束。

有帮助吗?

解决方案

对于您的示例,以下内容应该有效:

<parameter>
<parameterName value="@Oid" />
<dbType value="Guid" />
<layout type="log4net.Layout.RawPropertyLayout">
<key value="Id" />
</layout>
</parameter>

重要的是你将@id重命名为其他东西,否则你将在数据库中获得Null值,即使你试图插入字符串,

然后使用RawPropertyLayout存储,cus你不需要进行转换。

其他提示

1. 下载log4.net的源代码

2. 更改文件 log4net.Appender.AdoNetAppender.cs 中的函数 FormatValue ,如下所示:

virtual public void FormatValue(IDbCommand command, LoggingEvent loggingEvent)
        {
            // Lookup the parameter
            IDbDataParameter param = (IDbDataParameter)command.Parameters[m_parameterName];

            // Format the value
            object formattedValue = Layout.Format(loggingEvent);

            // If the value is null then convert to a DBNull
            if (formattedValue == null)
            {
                formattedValue = DBNull.Value;
            }

            if (param.DbType == System.Data.DbType.Guid)
            {
                param.Value = new Guid(formattedValue.ToString());
            }
            else
            {
                param.Value = formattedValue;
            }
        }

然后它有效!

如果您想获得通用GUID属性,可以执行以下操作:

    private void ConfigureLog4Net()
    {
        // adds a global custom log4net property
        log4net.GlobalContext.Properties[nameof(Guid.NewGuid)] = new NewGuidWrapper();

        // configures log4net by XML configurations from a .config file
        log4net.Config.XmlConfigurator.Configure();
    }

    private class NewGuidWrapper
    {
        // will return new GUID every time it's called
        public override string ToString() => Guid.NewGuid().ToString();
    }

然后您可以通过以下方式调用该属性:

<layout type="log4net.Layout.PatternLayout">
  <!-- if you want to format the layout as a GUID followed by a message  -->
  <conversionPattern value="%property{NewGuid} %m%n" />
</layout>

您也可以将这种类型的布局用于自定义数据库参数,如此处所述。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top