Skip to content

Commit 74a9faa

Browse files
committed
PostSharp.Samples.Logging.ElasticStack: work with development build.
1 parent f17e780 commit 74a9faa

18 files changed

+193
-95
lines changed

.gitignore

+3
Original file line numberDiff line numberDiff line change
@@ -234,3 +234,6 @@ _Pvt_Extensions
234234

235235
# FAKE - F# Make
236236
.fake/
237+
238+
239+
.idea

Diagnostics/PostSharp.Samples.Logging.ElasticStack/ApplicationInsightsLib/ApplicationInsightsExtensions.cs

+1-3
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
11
using Microsoft.ApplicationInsights.Channel;
22
using Microsoft.ApplicationInsights.DataContracts;
3-
using Microsoft.ApplicationInsights.Extensibility;
43
using Serilog;
54
using Serilog.Configuration;
65
using Serilog.Events;
76
using Serilog.ExtensionMethods;
87
using System;
9-
using System.Linq;
108

119
namespace ApplicationInsightsLib
1210
{
@@ -41,7 +39,7 @@ private static ITelemetry LogEventToTelemetryConverter(LogEvent logEvent, IForma
4139
includeMessageTemplateAsProperty: false);
4240
}
4341

44-
ISupportProperties telemetryProperties = (ISupportProperties)telemetry;
42+
var telemetryProperties = (ISupportProperties)telemetry;
4543

4644

4745
if (logEvent.Properties.ContainsKey("operation_Id"))

Diagnostics/PostSharp.Samples.Logging.ElasticStack/ApplicationInsightsLib/ApplicationInsightsLib.csproj

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
1-
<Project Sdk="Microsoft.NET.Sdk">
1+
<Project Sdk="Microsoft.NET.Sdk">
22

33
<PropertyGroup>
44
<TargetFramework>netcoreapp2.1</TargetFramework>
5+
<Configurations>Debug;Release;Development</Configurations>
6+
<Platforms>AnyCPU</Platforms>
57
</PropertyGroup>
68

79
<ItemGroup>
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,53 @@
1-
<Project Sdk="Microsoft.NET.Sdk">
1+
<Project>
22

33

44
<PropertyGroup>
55
<OutputType>Exe</OutputType>
66
<TargetFramework>netcoreapp2.1</TargetFramework>
77
<LangVersion>7.2</LangVersion>
8+
<Platforms>AnyCPU</Platforms>
9+
<Configurations >Debug;Release;Development</Configurations>
10+
<PostSharpBuild Condition="'$(Configuration)'=='Development'">Debug</PostSharpBuild>
811
</PropertyGroup>
912

13+
<Import Project="Sdk.props" Sdk="Microsoft.NET.Sdk" />
1014

1115
<ItemGroup>
12-
<PackageReference Include="PostSharp.Patterns.Diagnostics" Version="6.1.6-preview" />
13-
<PackageReference Include="PostSharp.Patterns.Diagnostics.Serilog" Version="6.1.6-preview" />
1416
<PackageReference Include="Serilog.Extensions.Logging" Version="2.0.2" />
1517
<PackageReference Include="Serilog.Sinks.Async" Version="1.3.0" />
1618
<PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" />
1719
<PackageReference Include="Serilog.Sinks.Http" Version="5.0.0" />
1820
</ItemGroup>
21+
22+
<ItemGroup Condition="'$(Configuration)'!='Development'">
23+
<PackageReference Include="PostSharp.Patterns.Diagnostics" Version="6.1.6-preview" />
24+
<PackageReference Include="PostSharp.Patterns.Diagnostics.Serilog" Version="6.1.6-preview" />
25+
<PackageReference Include="PostSharp.Patterns.Diagnostics.ApplicationInsights" Version="6.1.6-preview" />
26+
</ItemGroup>
27+
28+
<ItemGroup Condition="'$(Configuration)'=='Development'">
29+
<Reference Include="PostSharp">
30+
<HintPath>C:\src\postsharp\Build\bin\bin.Debug\netstandard2.0\PostSharp.dll</HintPath>
31+
</Reference>
32+
<Reference Include="PostSharp.Patterns.Common">
33+
<HintPath>C:\src\postsharp\Patterns\Build\bin\Debug\netstandard2.0\PostSharp.Patterns.Common.dll</HintPath>
34+
</Reference>
35+
<Reference Include="PostSharp.Patterns.Diagnostics">
36+
<HintPath>C:\src\postsharp\Patterns\Build\bin\Debug\netstandard2.0\PostSharp.Patterns.Diagnostics.dll</HintPath>
37+
</Reference>
38+
<Reference Include="PostSharp.Patterns.Diagnostics.Backends.ApplicationInsights">
39+
<HintPath>C:\src\postsharp\Patterns\Build\bin\Debug\netstandard2.0\PostSharp.Patterns.Diagnostics.Backends.ApplicationInsights.dll</HintPath>
40+
</Reference>
41+
<Reference Include="PostSharp.Patterns.Diagnostics.Backends.Serilog">
42+
<HintPath>C:\src\postsharp\Patterns\Build\bin\Debug\netstandard2.0\PostSharp.Patterns.Diagnostics.Backends.Serilog.dll</HintPath>
43+
</Reference>
44+
<PostSharpAddIn Include="C:\src\postsharp\Patterns\Build\bin\Debug\PostSharp.Patterns.Common.Weaver.dll"/>
45+
</ItemGroup>
46+
47+
<Import Project="Sdk.targets" Sdk="Microsoft.NET.Sdk" />
48+
49+
<Import Project="C:\src\postsharp\Build\bin\PostSharp.targets" Condition="'$(Configuration)'=='Development'" />
50+
1951

2052

2153
</Project>

Diagnostics/PostSharp.Samples.Logging.ElasticStack/ClientExample/InstrumentOutgoingRequestsAspect.cs

+15-17
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
using PostSharp.Aspects;
66
using PostSharp.Patterns.Diagnostics;
77
using PostSharp.Serialization;
8-
using Serilog.Context;
8+
using static PostSharp.Patterns.Diagnostics.SemanticMessageBuilder;
99

1010
[assembly: InstrumentOutgoingRequestsAspect( AttributeTargetAssemblies = "System.Net.Http",
1111
AttributeTargetTypes = "System.Net.Http.HttpClient",
@@ -16,27 +16,24 @@ namespace ClientExample
1616
[PSerializable]
1717
internal class InstrumentOutgoingRequestsAspect : MethodInterceptionAspect
1818
{
19-
private static readonly Logger logger = Logger.GetLogger( LoggingRoles.Tracing, typeof( HttpClient ) );
20-
21-
19+
private static readonly LogSource logger = LogSource.Get();
2220

2321
public override async Task OnInvokeAsync( MethodInterceptionArgs args )
2422
{
25-
HttpClient http = (HttpClient) args.Instance;
26-
27-
string operationId = Guid.NewGuid().ToString();
28-
29-
http.DefaultRequestHeaders.Remove( "Request-Id" );
30-
http.DefaultRequestHeaders.Add( "Request-Id", operationId.ToString() );
23+
var http = (HttpClient) args.Instance;
3124

32-
string verb = Trim( args.Method.Name, "Async" );
25+
26+
var verb = Trim( args.Method.Name, "Async" );
3327

34-
using ( LogContext.PushProperty( "OperationId", operationId ) )
35-
using ( LogActivity activity = logger.OpenActivity( "{Verb} {Url}", verb, args.Arguments[0] ) )
28+
using ( var activity = logger.Default.OpenActivity( Semantic( verb, ("Url", args.Arguments[0] ) ) ) )
3629
{
3730
try
3831
{
39-
Task t = base.OnInvokeAsync( args );
32+
33+
http.DefaultRequestHeaders.Remove( "Request-Id" );
34+
http.DefaultRequestHeaders.Add( "Request-Id", activity.ContextId );
35+
36+
var t = base.OnInvokeAsync( args );
4037

4138
// We need to call Suspend/Resume because we're calling LogActivity from an aspect and
4239
// aspects are not automatically enhanced.
@@ -55,15 +52,16 @@ public override async Task OnInvokeAsync( MethodInterceptionArgs args )
5552
}
5653

5754

58-
HttpResponseMessage response = (HttpResponseMessage) args.ReturnValue;
55+
var response = (HttpResponseMessage) args.ReturnValue;
5956

57+
6058
if ( response.IsSuccessStatusCode )
6159
{
62-
activity.SetSuccess( "Success: {StatusCode}", response.StatusCode );
60+
activity.SetOutcome( LogLevel.Info, Semantic( "Succeeded", ("StatusCode", response.StatusCode)));
6361
}
6462
else
6563
{
66-
activity.SetFailure( "Failure: {StatusCode}", response.StatusCode );
64+
activity.SetOutcome( LogLevel.Warning, Semantic( "Failed", ("StatusCode", response.StatusCode)));
6765
}
6866

6967
}

Diagnostics/PostSharp.Samples.Logging.ElasticStack/ClientExample/Program.cs

+7-9
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,4 @@
11
using System;
2-
using System.Diagnostics;
3-
using System.Net.Http;
4-
using System.Threading;
52
using System.Threading.Tasks;
63
using PostSharp.Patterns.Diagnostics;
74
using PostSharp.Patterns.Diagnostics.Backends.Serilog;
@@ -13,23 +10,24 @@
1310

1411
namespace ClientExample
1512
{
16-
public class Program
13+
public static class Program
1714
{
18-
19-
static async Task Main()
15+
private static async Task Main()
2016
{
21-
Serilog.Core.Logger logger = new LoggerConfiguration()
17+
var logger = new LoggerConfiguration()
2218
.Enrich.WithProperty( "Application", "ClientExample" )
23-
.Enrich.FromLogContext()
2419
.MinimumLevel.Debug()
2520
.WriteTo.Async( a => a.DurableHttp( requestUri: "http://localhost:31311", batchFormatter: new ArrayBatchFormatter(), batchPostingLimit: 5 ) )
2621
.WriteTo.Console( outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level:u3}] {Indent:l}{Message:l}{NewLine}{Exception}" )
2722
.CreateLogger();
2823

2924

30-
SerilogLoggingBackend backend = new SerilogLoggingBackend( logger );
25+
var backend = new SerilogLoggingBackend( logger );
26+
LoggingServices.Roles["Custom"].CustomRecordLoggingOptions.IncludeExecutionTime = true;
3127
backend.Options.IncludeExceptionDetails = true;
3228
backend.Options.SemanticParametersTreatedSemantically |= SemanticParameterKind.MemberName;
29+
backend.Options.AddEventIdProperty = true;
30+
backend.Options.ContextIdGenerationStrategy = LoggingOperationIdGenerationStrategy.Hierarchical;
3331
LoggingServices.DefaultBackend = backend;
3432

3533
using ( logger )

Diagnostics/PostSharp.Samples.Logging.ElasticStack/ClientExample/QueueProcessor.cs

+3-6
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,8 @@
11
using System;
2-
using System.Diagnostics;
32
using System.Net.Http;
43
using System.Text;
5-
using System.Threading;
64
using System.Threading.Tasks;
75
using PostSharp.Patterns.Diagnostics;
8-
using Serilog.Context;
96

107
namespace ClientExample
118
{
@@ -39,8 +36,8 @@ private static async Task ProcessItem( QueueItem item )
3936
try
4037
{
4138

42-
string url = $"http://localhost:5005/api/values/{item.Id}";
43-
StringContent stringContent = item.Value == null ? null : new StringContent( "\"" + item.Value + "\"", Encoding.UTF8, "application/json" );
39+
var url = $"http://localhost:5005/api/values/{item.Id}";
40+
var stringContent = item.Value == null ? null : new StringContent( "\"" + item.Value + "\"", Encoding.UTF8, "application/json" );
4441
HttpResponseMessage response;
4542

4643

@@ -64,7 +61,7 @@ private static async Task ProcessItem( QueueItem item )
6461

6562
response.EnsureSuccessStatusCode();
6663

67-
string responseValue = await response.Content.ReadAsStringAsync();
64+
var responseValue = await response.Content.ReadAsStringAsync();
6865
}
6966
catch ( Exception e )
7067
{

Diagnostics/PostSharp.Samples.Logging.ElasticStack/MicroserviceExample.sln

+5
Original file line numberDiff line numberDiff line change
@@ -16,16 +16,21 @@ Global
1616
GlobalSection(SolutionConfigurationPlatforms) = preSolution
1717
Debug|Any CPU = Debug|Any CPU
1818
Release|Any CPU = Release|Any CPU
19+
Development|Any CPU = Development|Any CPU
1920
EndGlobalSection
2021
GlobalSection(ProjectConfigurationPlatforms) = postSolution
2122
{78C5D1D7-0A11-46CE-985A-051AF8E6D5ED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
2223
{78C5D1D7-0A11-46CE-985A-051AF8E6D5ED}.Debug|Any CPU.Build.0 = Debug|Any CPU
2324
{78C5D1D7-0A11-46CE-985A-051AF8E6D5ED}.Release|Any CPU.ActiveCfg = Release|Any CPU
2425
{78C5D1D7-0A11-46CE-985A-051AF8E6D5ED}.Release|Any CPU.Build.0 = Release|Any CPU
26+
{78C5D1D7-0A11-46CE-985A-051AF8E6D5ED}.Development|Any CPU.ActiveCfg = Development|Any CPU
27+
{78C5D1D7-0A11-46CE-985A-051AF8E6D5ED}.Development|Any CPU.Build.0 = Development|Any CPU
2528
{A8455DD8-A82C-4ED6-8E58-C54B41232CE2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
2629
{A8455DD8-A82C-4ED6-8E58-C54B41232CE2}.Debug|Any CPU.Build.0 = Debug|Any CPU
2730
{A8455DD8-A82C-4ED6-8E58-C54B41232CE2}.Release|Any CPU.ActiveCfg = Release|Any CPU
2831
{A8455DD8-A82C-4ED6-8E58-C54B41232CE2}.Release|Any CPU.Build.0 = Release|Any CPU
32+
{A8455DD8-A82C-4ED6-8E58-C54B41232CE2}.Development|Any CPU.ActiveCfg = Development|Any CPU
33+
{A8455DD8-A82C-4ED6-8E58-C54B41232CE2}.Development|Any CPU.Build.0 = Development|Any CPU
2934
EndGlobalSection
3035
GlobalSection(SolutionProperties) = preSolution
3136
HideSolutionNode = FALSE

Diagnostics/PostSharp.Samples.Logging.ElasticStack/MicroserviceExample/Controllers/ValuesController.cs

+1-3
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
using System;
22
using System.Collections.Generic;
33
using System.Collections.Concurrent;
4-
using System.Linq;
5-
using System.Threading.Tasks;
64
using Microsoft.AspNetCore.Mvc;
75

86
namespace MicroserviceExample.Controllers
@@ -29,7 +27,7 @@ public ActionResult<IEnumerable<KeyValuePair<int,string>>> Get()
2927
[HttpGet( "{id}" )]
3028
public ActionResult<string> Get( int id )
3129
{
32-
if ( this.values.TryGetValue( id, out string value ) )
30+
if ( this.values.TryGetValue( id, out var value ) )
3331
{
3432
return value;
3533
}

Diagnostics/PostSharp.Samples.Logging.ElasticStack/MicroserviceExample/ActionResultFormatter.cs renamed to Diagnostics/PostSharp.Samples.Logging.ElasticStack/MicroserviceExample/Formatters/ActionResultFormatter.cs

+4-23
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,8 @@
1-
using System;
2-
using System.Collections.Generic;
3-
using System.Linq;
4-
using System.Threading.Tasks;
5-
using Microsoft.AspNetCore.Mvc;
1+
using Microsoft.AspNetCore.Mvc;
62
using PostSharp.Patterns.Diagnostics;
73
using PostSharp.Patterns.Formatters;
84

9-
namespace MicroserviceExample
5+
namespace MicroserviceExample.Formatters
106
{
117
public class ActionResultFormatter<T> : Formatter<ActionResult<T>>
128
{
@@ -16,34 +12,19 @@ public override void Write( UnsafeStringBuilder stringBuilder, ActionResult<T> v
1612
}
1713
}
1814

19-
public class ObjectResultFormatter : Formatter<ObjectResult>
20-
{
21-
public override void Write(UnsafeStringBuilder stringBuilder, ObjectResult value )
22-
{
23-
if ( value.Value != null )
24-
{
25-
LoggingServices.Formatters.Get(value.Value.GetType() ).Write(stringBuilder, value.Value );
26-
}
27-
else
28-
{
29-
stringBuilder.Append("null" );
30-
}
31-
}
32-
}
33-
3415
public class ActionResultFormatter : Formatter<IActionResult>
3516
{
3617
public override void Write( UnsafeStringBuilder stringBuilder, IActionResult value )
3718
{
38-
IFormatter specificFormatter = LoggingServices.Formatters.Get(value.GetType() );
19+
var specificFormatter = LoggingServices.Formatters.Get(value.GetType() );
3920
if ( specificFormatter != this )
4021
{
4122
specificFormatter.Write(stringBuilder, value );
4223
}
4324
else
4425
{
4526
const string suffix = "Result";
46-
string name = value.GetType().Name;
27+
var name = value.GetType().Name;
4728

4829
if ( name.EndsWith(suffix ) )
4930
{
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
using Microsoft.AspNetCore.Mvc;
2+
using PostSharp.Patterns.Diagnostics;
3+
using PostSharp.Patterns.Formatters;
4+
5+
namespace MicroserviceExample.Formatters
6+
{
7+
public class ObjectResultFormatter : Formatter<ObjectResult>
8+
{
9+
public override void Write(UnsafeStringBuilder stringBuilder, ObjectResult value )
10+
{
11+
if ( value.Value != null )
12+
{
13+
LoggingServices.Formatters.Get(value.Value.GetType() ).Write(stringBuilder, value.Value );
14+
}
15+
else
16+
{
17+
stringBuilder.Append("null" );
18+
}
19+
}
20+
}
21+
}

0 commit comments

Comments
 (0)