Using uniqueidentifiers / guids as custom properties in log4net

I am trying to add a custom property that is a guide, but it gives me this error:

System.InvalidCastException: Failed to convert parameter value from string to manual. ---> System.InvalidCastException: invalid cast from 'System.String' to 'System.Guid'.

I indicate this in config:

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

The actual code (snippet) I'm using is this:

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

Any help please? :) The id field in the database is defined as uniqueidentifier NOT NULL, but it does not have a primary key.

+7
uniqueidentifier log4net
source share
2 answers

For your example, the following should work:

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

It is important that you rename @id to another, otherwise you will get Null values โ€‹โ€‹in the database, even if you try to insert rows,

And then use RawPropertyLayout for storage, as you do not need to do the conversion.

+22
source share

1. Download the source code for log4.net

2. Change the FormatValue function inside the log4net.Appender.AdoNetAppender.cs file as follows:

 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; } } 

then it works!

0
source share

All Articles