serilog / serilog-expressions

An embeddable mini-language for filtering, enriching, and formatting Serilog events, ideal for use with JSON or XML configuration.
Apache License 2.0
193 stars 17 forks source link

Fix crash on apps built with PublishTrimmed=True #110

Closed malciin closed 10 months ago

malciin commented 10 months ago

I've found that Serilog.Expressions produces nasty startup crash when an app that uses this lib is built with PublishTrimmed=true:

Unhandled exception. System.ArgumentException: The function name `Substring` was not recognized.
   at Serilog.Expressions.Compilation.Linq.LinqExpressionCompiler.Transform(CallExpression)
   at Serilog.Expressions.Compilation.Transformations.SerilogExpressionTransformer`1.Transform(Expression expression)
   at Serilog.Expressions.Compilation.Linq.LinqExpressionCompiler.Compile(Expression, IFormatProvider , NameResolver)
   at Serilog.Expressions.Compilation.ExpressionCompiler.Compile(Expression, IFormatProvider , NameResolver)
   at Serilog.Expressions.SerilogExpression.TryCompileImpl(String, IFormatProvider , NameResolver , CompiledExpression& , String& )
   at Serilog.Expressions.SerilogExpression.Compile(String, IFormatProvider , NameResolver )
   at Serilog.LoggerEnrichmentConfigurationExtensions.WithComputed(LoggerEnrichmentConfiguration, String, String)
   at Program.<>c.<<Main>$>b__0_1(HostBuilderContext _, LoggerConfiguration configuration) in D:\serilog-expressions-substring-error\Program.cs:line 7
   at Serilog.SerilogHostBuilderExtensions.<>c__DisplayClass1_0.<UseSerilog>b__0(HostBuilderContext hostBuilderContext, IServiceProvider services, LoggerConfiguration loggerConfiguration)
   at Serilog.SerilogHostBuilderExtensions.<>c__DisplayClass2_1.<UseSerilog>b__1(IServiceProvider services, LoggerConfiguration loggerConfiguration)
   at Serilog.SerilogServiceCollectionExtensions.<>c__DisplayClass3_0.<AddSerilog>b__0(IServiceProvider services)
   // rest stack unrelevant

Reproduction repo: https://github.com/malciin/serilog-expressions-trim-crash

I've investigated it and found that's because _nameResolver does not have any operator registered in it at all because those operators are trimmed away.

https://github.com/serilog/serilog-expressions/blob/ccb6b01f9cc2bff5f8fc0a8ea6fc0f7e9792618f/src/Serilog.Expressions/Expressions/Compilation/Linq/LinqExpressionCompiler.cs#L102

Adding [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] to StaticMemberNameResolver fixes it.

Repo with fixed app: https://github.com/malciin/serilog-expressions/tree/dev-trimmed-test-app/src/SerilogTrimTestApp

nblumhardt commented 10 months ago

Excellent, thank you.