I have defined two Filters for a serilog LoggerConfiguration
Both are RollingFile loggers which should, depending on the type write in a log file in another folder.
var activityPath = @"C:\temp\Activities\log-{Date}.log";
var eventsPath = @"C:\temp\Events\log-{Date}.log";
loggerConfig.WriteTo.Logger(
lc =>
lc.Filter.ByExcluding(Matching.FromSource<EventLogItem>())
.WriteTo.RollingFile(pathFormat: eventsPath,
fileSizeLimitBytes: 1073741824,
retainedFileCountLimit: 31));
loggerConfig.WriteTo.Logger(
lc =>
lc.Filter.ByExcluding(Matching.FromSource<ActivityLogItem>())
.WriteTo.RollingFile(pathFormat: activityPath,
fileSizeLimitBytes: 1073741824,
retainedFileCountLimit: 31));
_logger.Information("{@ActivityLogItem}", new ActivityLogItem());
_logger.Information("{@EventLogItem}", new EventLogItem());
When i'm logging with this configuration both files in both folders are generated but the files contain both the entries for the EventLogItem
and the ActivityLogItem
.
File: Activities\log-2016....log
2016-12-29 17:36:47.610 +01:00 [Information] EventLogItem { Id: 00000000-0000-0000-0000-000000000000, TimeStamp: 01/01/0001 00:00:00, Title: "Startup", Detail: "Starting up" } 2016-12-29 17:57:32.297
+01:00 [Information] ActivityLogItem { Ip: "::1", Port: "-1", UserAgent: "Mozilla/5.0", StartRequest: 12/29/2016 17:57:29, EndRequest: 12/29/2016 17:57:29 }
File: Events\log-2016....log
2016-12-29 17:36:47.610 +01:00 [Information] EventLogItem { Id: 00000000-0000-0000-0000-000000000000, TimeStamp: 01/01/0001 00:00:00, Title: "Startup", Detail: "Starting up" } 2016-12-29 17:57:32.297
+01:00 [Information] ActivityLogItem { Ip: "::1", Port: "-1", UserAgent: "Mozilla/5.0", StartRequest: 12/29/2016 17:57:29, EndRequest: 12/29/2016 17:57:29 }
I have also tried it with ByIncludingOnly
at the Filter configuration, which resulted in the result that no file was generated.
How should my configuration look like that serilog will log on different files for a type?
Edit:
I have also tried it now by adding a Matching.WithProperty
In my class ActivityLogItem
I have added a new property:
public int EType {get;set;} = 1;
and changed the configuration to
ByExcluding(Matching.WithProperty<int>("EType", p => p == 1)
which is also getting ignored. The logger writes both entries in both files specified.
The
FromSource()
filter identifies events raised by a particular logger:The
WithProperty()
filter looks at the direct properties on the log events, i.e. the names embedded in the message template like{@ActivityLogItem}
. In your follow-up edit, theEType
property is a nested property, so won't match the filter.You could do the following if you want to use that approach:
There are several ways to set up the filtering; I'd recommend the
ForContext()
approach if it is open to you. Alternatively, if you don't want to modify the logging statements, try: