Skip to content

Commit

Permalink
Implement the Microsoft ILogger interface to push logs to skywalking (#…
Browse files Browse the repository at this point in the history
…502)

* feat : Add logging to skywalking

* feat : Modify class library name

* feat : 适配不通的.net 版本
  • Loading branch information
KawhiWei authored Sep 4, 2022
1 parent 5854022 commit 7b3119d
Show file tree
Hide file tree
Showing 14 changed files with 288 additions and 19 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using Microsoft.AspNetCore.Mvc;

namespace SkyApm.Sample.Logging.Controllers;

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

private readonly ILogger<WeatherForecastController> _logger;

public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}

[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
_logger.LogInformation("查询时间");

return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
25 changes: 25 additions & 0 deletions sample/SkyApm.Sample.Logging/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();
15 changes: 15 additions & 0 deletions sample/SkyApm.Sample.Logging/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"profiles": {
"SkyApm.Sample.Logging": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7126;http://localhost:5021",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "SkyAPM.Agent.AspNetCore"
}
}
}
}
20 changes: 20 additions & 0 deletions sample/SkyApm.Sample.Logging/SkyApm.Sample.Logging.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\SkyApm.Agent.AspNetCore\SkyApm.Agent.AspNetCore.csproj" />
</ItemGroup>
<ItemGroup>
<Content Update="skyapm.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project>
12 changes: 12 additions & 0 deletions sample/SkyApm.Sample.Logging/WeatherForecast.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
namespace SkyApm.Sample.Logging;

public class WeatherForecast
{
public DateTime Date { get; set; }

public int TemperatureC { get; set; }

public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);

public string? Summary { get; set; }
}
8 changes: 8 additions & 0 deletions sample/SkyApm.Sample.Logging/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
9 changes: 9 additions & 0 deletions sample/SkyApm.Sample.Logging/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
30 changes: 30 additions & 0 deletions sample/SkyApm.Sample.Logging/skyapm.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"SkyWalking": {
"ServiceName": "asp-net-core-backend-logging",
"Namespace": "",
"HeaderVersions": [
"sw8"
],
"Sampling": {
"SamplePer3Secs": -1,
"Percentage": -1.0,
"LogSqlParameterValue": false
},
"Logging": {
"Level": "Information",
"FilePath": "logs/skyapm-{Date}.log"
},
"Transport": {
"Interval": 3000,
"ProtocolVersion": "v8",
"QueueSize": 30000,
"BatchSize": 3000,
"gRPC": {
"Servers": "192.168.31.10:30102",
"Timeout": 100000,
"ConnectTimeout": 100000,
"ReportTimeout": 600000
}
}
}
}
14 changes: 14 additions & 0 deletions skyapm-dotnet.sln
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SkyApm.Diagnostics.FreeSql"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SkyApm.Sample.FreeSqlSqlite", "sample\SkyApm.Sample.FreeSql\SkyApm.Sample.FreeSqlSqlite.csproj", "{B1EF3295-4BF0-489F-8063-C9E3DAE20AA9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SkyApm.Diagnostics.MSLogging", "src\SkyApm.Diagnostics.MSLogging\SkyApm.Diagnostics.MSLogging.csproj", "{4E3BA76C-2A30-4CAD-9F6C-08DF5DF0CE0C}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SkyApm.Sample.Logging", "sample\SkyApm.Sample.Logging\SkyApm.Sample.Logging.csproj", "{136EAD07-A501-4308-9972-82E44F655735}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -243,6 +247,14 @@ Global
{B1EF3295-4BF0-489F-8063-C9E3DAE20AA9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B1EF3295-4BF0-489F-8063-C9E3DAE20AA9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B1EF3295-4BF0-489F-8063-C9E3DAE20AA9}.Release|Any CPU.Build.0 = Release|Any CPU
{4E3BA76C-2A30-4CAD-9F6C-08DF5DF0CE0C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4E3BA76C-2A30-4CAD-9F6C-08DF5DF0CE0C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4E3BA76C-2A30-4CAD-9F6C-08DF5DF0CE0C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4E3BA76C-2A30-4CAD-9F6C-08DF5DF0CE0C}.Release|Any CPU.Build.0 = Release|Any CPU
{136EAD07-A501-4308-9972-82E44F655735}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{136EAD07-A501-4308-9972-82E44F655735}.Debug|Any CPU.Build.0 = Debug|Any CPU
{136EAD07-A501-4308-9972-82E44F655735}.Release|Any CPU.ActiveCfg = Release|Any CPU
{136EAD07-A501-4308-9972-82E44F655735}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -289,6 +301,8 @@ Global
{8D3C5573-C282-45F5-A7F4-2E323F322CB7} = {B5E677CF-2920-4B0A-A056-E73F6B2CF2BC}
{82580A47-9DBC-43E8-B581-0C35147B4FAD} = {B5E677CF-2920-4B0A-A056-E73F6B2CF2BC}
{B1EF3295-4BF0-489F-8063-C9E3DAE20AA9} = {844CEACD-4C85-4B15-9E2B-892B01FDA4BB}
{4E3BA76C-2A30-4CAD-9F6C-08DF5DF0CE0C} = {B5E677CF-2920-4B0A-A056-E73F6B2CF2BC}
{136EAD07-A501-4308-9972-82E44F655735} = {844CEACD-4C85-4B15-9E2B-892B01FDA4BB}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {94C0DA2C-CCCB-4314-93A2-9809B5DD0583}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
using SkyApm.Diagnostics.Grpc.Net.Client;
using SkyApm.Diagnostics.HttpClient;
using SkyApm.Diagnostics.SqlClient;
using SkyApm.Logging;
using SkyApm.Sampling;
using SkyApm.Service;
using SkyApm.Tracing;
Expand All @@ -34,8 +33,12 @@
using SkyApm.Utilities.DependencyInjection;
using SkyApm.Utilities.Logging;
using System;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using SkyApm;
using SkyApm.Agent.Hosting;
using SkyApm.Diagnostics.MSLogging;
using ILoggerFactory = SkyApm.Logging.ILoggerFactory;

namespace Microsoft.Extensions.DependencyInjection
{
Expand Down Expand Up @@ -102,6 +105,7 @@ public static IServiceCollection AddSkyApmLogger(this IServiceCollection service
{
services.AddSingleton<ISkyApmLogDispatcher, AsyncQueueSkyApmLogDispatcher>();
services.AddSingleton<ILoggerContextContextMapper, LoggerContextContextMapper>();
services.TryAddEnumerable(ServiceDescriptor.Singleton<ILoggerProvider, SkyApmLoggerProvider>());
return services;
}

Expand Down
37 changes: 19 additions & 18 deletions src/SkyApm.Agent.Hosting/SkyApm.Agent.Hosting.csproj
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="..\..\build\common.props"/>
<Import Project="..\..\build\common.props" />
<PropertyGroup>
<Description>$(Product) ASP.NET Core Agent.</Description>
<AssemblyTitle>$(PackagePrefix).Agent.Hosting</AssemblyTitle>
Expand All @@ -12,28 +12,29 @@
<TargetFrameworks>netcoreapp3.1;net5.0;net6.0</TargetFrameworks>
</PropertyGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'netcoreapp3.1'">
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="3.1.0" PrivateAssets="All"/>
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="3.1.0" PrivateAssets="All" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net5.0'">
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="5.0.0"/>
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="5.0.0" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net6.0'">
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="6.0.0"/>
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="6.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SkyApm.Abstractions\SkyApm.Abstractions.csproj"/>
<ProjectReference Include="..\SkyApm.Diagnostics.EntityFrameworkCore.Npgsql\SkyApm.Diagnostics.EntityFrameworkCore.Npgsql.csproj"/>
<ProjectReference Include="..\SkyApm.Diagnostics.EntityFrameworkCore.Pomelo.MySql\SkyApm.Diagnostics.EntityFrameworkCore.Pomelo.MySql.csproj"/>
<ProjectReference Include="..\SkyApm.Diagnostics.EntityFrameworkCore.Sqlite\SkyApm.Diagnostics.EntityFrameworkCore.Sqlite.csproj"/>
<ProjectReference Include="..\SkyApm.Diagnostics.EntityFrameworkCore\SkyApm.Diagnostics.EntityFrameworkCore.csproj"/>
<ProjectReference Include="..\SkyApm.Core\SkyApm.Core.csproj"/>
<ProjectReference Include="..\SkyApm.Diagnostics.Grpc.Net.Client\SkyApm.Diagnostics.Grpc.Net.Client.csproj"/>
<ProjectReference Include="..\SkyApm.Diagnostics.Grpc\SkyApm.Diagnostics.Grpc.csproj"/>
<ProjectReference Include="..\SkyApm.Diagnostics.HttpClient\SkyApm.Diagnostics.HttpClient.csproj"/>
<ProjectReference Include="..\SkyApm.Diagnostics.SqlClient\SkyApm.Diagnostics.SqlClient.csproj"/>
<ProjectReference Include="..\SkyApm.Transport.Grpc\SkyApm.Transport.Grpc.csproj"/>
<ProjectReference Include="..\SkyApm.Utilities.Configuration\SkyApm.Utilities.Configuration.csproj"/>
<ProjectReference Include="..\SkyApm.Utilities.DependencyInjection\SkyApm.Utilities.DependencyInjection.csproj"/>
<ProjectReference Include="..\SkyApm.Utilities.Logging\SkyApm.Utilities.Logging.csproj"/>
<ProjectReference Include="..\SkyApm.Abstractions\SkyApm.Abstractions.csproj" />
<ProjectReference Include="..\SkyApm.Diagnostics.EntityFrameworkCore.Npgsql\SkyApm.Diagnostics.EntityFrameworkCore.Npgsql.csproj" />
<ProjectReference Include="..\SkyApm.Diagnostics.EntityFrameworkCore.Pomelo.MySql\SkyApm.Diagnostics.EntityFrameworkCore.Pomelo.MySql.csproj" />
<ProjectReference Include="..\SkyApm.Diagnostics.EntityFrameworkCore.Sqlite\SkyApm.Diagnostics.EntityFrameworkCore.Sqlite.csproj" />
<ProjectReference Include="..\SkyApm.Diagnostics.EntityFrameworkCore\SkyApm.Diagnostics.EntityFrameworkCore.csproj" />
<ProjectReference Include="..\SkyApm.Core\SkyApm.Core.csproj" />
<ProjectReference Include="..\SkyApm.Diagnostics.Grpc.Net.Client\SkyApm.Diagnostics.Grpc.Net.Client.csproj" />
<ProjectReference Include="..\SkyApm.Diagnostics.Grpc\SkyApm.Diagnostics.Grpc.csproj" />
<ProjectReference Include="..\SkyApm.Diagnostics.HttpClient\SkyApm.Diagnostics.HttpClient.csproj" />
<ProjectReference Include="..\SkyApm.Diagnostics.MSLogging\SkyApm.Diagnostics.MSLogging.csproj" />
<ProjectReference Include="..\SkyApm.Diagnostics.SqlClient\SkyApm.Diagnostics.SqlClient.csproj" />
<ProjectReference Include="..\SkyApm.Transport.Grpc\SkyApm.Transport.Grpc.csproj" />
<ProjectReference Include="..\SkyApm.Utilities.Configuration\SkyApm.Utilities.Configuration.csproj" />
<ProjectReference Include="..\SkyApm.Utilities.DependencyInjection\SkyApm.Utilities.DependencyInjection.csproj" />
<ProjectReference Include="..\SkyApm.Utilities.Logging\SkyApm.Utilities.Logging.csproj" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>netcoreapp3.1;net5.0;net6.0</TargetFrameworks>
<RootNamespace>SkyApm.Diagnostics.MSLogging</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="6.0.1"/>
</ItemGroup>

<ItemGroup Condition="'$(TargetFramework)' == 'netcoreapp3.1'">
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="3.1.0"/>
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net5.0'">
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="5.0.0"/>
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net6.0'">
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="6.0.1"/>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SkyApm.Abstractions\SkyApm.Abstractions.csproj"/>
</ItemGroup>
</Project>
42 changes: 42 additions & 0 deletions src/SkyApm.Diagnostics.MSLogging/SkyApmLogger.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using SkyApm.Tracing;
using SkyApm.Tracing.Segments;
using SkyApm.Transport;

namespace SkyApm.Diagnostics.MSLogging
{
public class SkyApmLogger : ILogger
{
private readonly string _categoryName;
private readonly ISkyApmLogDispatcher _skyApmLogDispatcher;
private readonly IEntrySegmentContextAccessor _entrySegmentContextAccessor;

public SkyApmLogger(string categoryName, ISkyApmLogDispatcher skyApmLogDispatcher, IEntrySegmentContextAccessor entrySegmentContextAccessor)
{
_categoryName = categoryName;
_skyApmLogDispatcher = skyApmLogDispatcher;
_entrySegmentContextAccessor = entrySegmentContextAccessor;
}

public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{
var logs = new Dictionary<string, object>();
logs.Add("className", _categoryName);
logs.Add("Level", logLevel);
logs.Add("logMessage", state.ToString() ?? "");
var logContext = new LoggerContext()
{
Logs = logs,
SegmentContext = _entrySegmentContextAccessor.Context,
};
_skyApmLogDispatcher.Dispatch(logContext);
}

public bool IsEnabled(LogLevel logLevel) => true;


public IDisposable BeginScope<TState>(TState state) => default!;
}
}
32 changes: 32 additions & 0 deletions src/SkyApm.Diagnostics.MSLogging/SkyApmLoggerProvider.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using System.Collections.Concurrent;
using Microsoft.Extensions.Logging;
using SkyApm.Tracing;
using SkyApm.Transport;

namespace SkyApm.Diagnostics.MSLogging
{
public class SkyApmLoggerProvider: ILoggerProvider
{
private ConcurrentDictionary<string, SkyApmLogger> _doveLoggers = new ConcurrentDictionary<string, SkyApmLogger>();
private readonly ISkyApmLogDispatcher _skyApmLogDispatcher;
private readonly IEntrySegmentContextAccessor _entrySegmentContextAccessor;

public SkyApmLoggerProvider(ISkyApmLogDispatcher skyApmLogDispatcher,IEntrySegmentContextAccessor entrySegmentContextAccessor)
{
_skyApmLogDispatcher = skyApmLogDispatcher;
_entrySegmentContextAccessor = entrySegmentContextAccessor;

}

public void Dispose()
{

}

public ILogger CreateLogger(string categoryName)
{
return _doveLoggers.GetOrAdd(categoryName,_=>new SkyApmLogger(categoryName,_skyApmLogDispatcher,_entrySegmentContextAccessor));
}
}
}

0 comments on commit 7b3119d

Please sign in to comment.