Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor MSLogging extensions and add log samples #513

Merged
merged 3 commits into from
Sep 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions sample/SkyApm.Sample.GenericHost/LogWorker.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace SkyApm.Sample.GenericHost
{
public class LogWorker: BackgroundService
{

private readonly ILogger<LogWorker> _logger;

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

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await Task.Delay(1000, stoppingToken);
_logger.LogInformation("LogWorker running at: {}", DateTime.Now);
}
}
}
}
3 changes: 2 additions & 1 deletion sample/SkyApm.Sample.GenericHost/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ public static void Main(string[] args)

static IHostBuilder CreateHostBuilder(string[] args) =>
new HostBuilder()
.ConfigureServices(services => services.AddHostedService<Worker>())
.ConfigureServices(services => services.AddHostedService<Worker>().AddHostedService<LogWorker>()
)
.AddSkyAPM();
}
}
4 changes: 0 additions & 4 deletions src/SkyApm.Abstractions/Transport/LoggerRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,5 @@ public class LoggerSegmentReference
public string SegmentId { get; set; }

public string TraceId { get; set; }

public string ServiceId { get; set; }

public string ServiceInstanceId { get; set; }
}
}
30 changes: 11 additions & 19 deletions src/SkyApm.Agent.Hosting/Extensions/ServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,6 @@
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;
Expand All @@ -49,10 +47,8 @@ public static IServiceCollection AddSkyAPM(this IServiceCollection services, Act
services.AddSkyAPMCore(extensionsSetup);
return services;
}



internal static IServiceCollection AddSkyAPMCore(this IServiceCollection services, Action<SkyApmExtensions> extensionsSetup = null)
private static IServiceCollection AddSkyAPMCore(this IServiceCollection services, Action<SkyApmExtensions> extensionsSetup = null)
{
if (services == null)
{
Expand All @@ -72,13 +68,15 @@ internal static IServiceCollection AddSkyAPMCore(this IServiceCollection service
services.AddSingleton<IConfigurationFactory, ConfigurationFactory>();
services.AddSingleton<IHostedService, InstrumentationHostedService>();
services.AddSingleton<IEnvironmentProvider, HostingEnvironmentProvider>();
services.AddTracing().AddSkyApmLogger().AddSampling().AddGrpcTransport().AddSkyApmLogging();
services.AddSingleton<ISkyApmLogDispatcher, AsyncQueueSkyApmLogDispatcher>();
services.AddTracing().AddSampling().AddGrpcTransport().AddSkyApmLogging();
var extensions = services.AddSkyApmExtensions()
.AddHttpClient()
.AddGrpcClient()
.AddSqlClient()
.AddGrpc()
.AddEntityFrameworkCore(c => c.AddPomeloMysql().AddNpgsql().AddSqlite());
.AddHttpClient()
.AddGrpcClient()
.AddSqlClient()
.AddGrpc()
.AddEntityFrameworkCore(c => c.AddPomeloMysql().AddNpgsql().AddSqlite())
.AddMSLogging();

extensionsSetup?.Invoke(extensions);

Expand All @@ -94,20 +92,14 @@ private static IServiceCollection AddTracing(this IServiceCollection services)
services.AddSingleton<IEntrySegmentContextAccessor, EntrySegmentContextAccessor>();
services.AddSingleton<ILocalSegmentContextAccessor, LocalSegmentContextAccessor>();
services.AddSingleton<IExitSegmentContextAccessor, ExitSegmentContextAccessor>();
services.AddSingleton<ISegmentContextAccessor, SegmentContextAccessor>();
services.AddSingleton<ISamplerChainBuilder, SamplerChainBuilder>();
services.AddSingleton<IUniqueIdGenerator, UniqueIdGenerator>();
services.AddSingleton<ISegmentContextMapper, SegmentContextMapper>();
services.AddSingleton<IBase64Formatter, Base64Formatter>();
return services;
}

public static IServiceCollection AddSkyApmLogger(this IServiceCollection services)
{
services.AddSingleton<ISkyApmLogDispatcher, AsyncQueueSkyApmLogDispatcher>();
services.TryAddEnumerable(ServiceDescriptor.Singleton<ILoggerProvider, SkyApmLoggerProvider>());
return services;
}


private static IServiceCollection AddSampling(this IServiceCollection services)
{
services.AddSingleton<SimpleCountSamplingInterceptor>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,17 @@
<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"/>
<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"/>
<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"/>
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="6.0.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SkyApm.Abstractions\SkyApm.Abstractions.csproj"/>
<ProjectReference Include="..\SkyApm.Abstractions\SkyApm.Abstractions.csproj" />
<ProjectReference Include="..\SkyApm.Utilities.DependencyInjection\SkyApm.Utilities.DependencyInjection.csproj" />
</ItemGroup>
</Project>
4 changes: 1 addition & 3 deletions src/SkyApm.Diagnostics.MSLogging/SkyApmLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,7 @@ public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Except
: new LoggerSegmentReference()
{
TraceId = segmentContext.TraceId,
SegmentId = segmentContext.SegmentId,
ServiceId = segmentContext.ServiceId,
ServiceInstanceId = segmentContext.ServiceInstanceId
SegmentId = segmentContext.SegmentId
},
};
_skyApmLogDispatcher.Dispatch(logContext);
Expand Down
17 changes: 17 additions & 0 deletions src/SkyApm.Diagnostics.MSLogging/SkyWalkingBuilderExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using SkyApm.Transport;
using SkyApm.Utilities.DependencyInjection;

namespace SkyApm.Diagnostics.MSLogging
{
public static class SkyWalkingBuilderExtensions
{
public static SkyApmExtensions AddMSLogging(this SkyApmExtensions extensions)
{
extensions.Services.TryAddEnumerable(ServiceDescriptor.Singleton<ILoggerProvider, SkyApmLoggerProvider>());
return extensions;
}
}
}
28 changes: 17 additions & 11 deletions src/SkyApm.Transport.Grpc/V8/LoggerReporter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
Expand All @@ -33,17 +34,18 @@ public class LoggerReporter : ILoggerReporter
{
private readonly ConnectionManager _connectionManager;
private readonly ILogger _logger;
private readonly GrpcConfig _config;
private readonly GrpcConfig _grpcConfig;
private readonly InstrumentConfig _instrumentConfig;

public LoggerReporter(ConnectionManager connectionManager, IConfigAccessor configAccessor,
ILoggerFactory loggerFactory)
{
_connectionManager = connectionManager;
_config = configAccessor.Get<GrpcConfig>();
_grpcConfig = configAccessor.Get<GrpcConfig>();
_instrumentConfig = configAccessor.Get<InstrumentConfig>();
_logger = loggerFactory.CreateLogger(typeof(SegmentReporter));
}



public async Task ReportAsync(IReadOnlyCollection<LoggerRequest> loggerRequests,
CancellationToken cancellationToken = default)
{
Expand All @@ -57,8 +59,8 @@ public async Task ReportAsync(IReadOnlyCollection<LoggerRequest> loggerRequests,
{
var stopwatch = Stopwatch.StartNew();
var client = new LogReportService.LogReportServiceClient(connection);
using (var asyncClientStreamingCall =
client.collect(_config.GetMeta(), _config.GetReportTimeout(), cancellationToken))
using (var asyncClientStreamingCall = client.collect(_grpcConfig.GetMeta(),
_grpcConfig.GetReportTimeout(), cancellationToken))
{
foreach (var loggerRequest in loggerRequests)
{
Expand All @@ -72,13 +74,13 @@ public async Task ReportAsync(IReadOnlyCollection<LoggerRequest> loggerRequests,
{
TraceContext = new TraceContext()
{
TraceId = loggerRequest.SegmentReference.TraceId,
TraceSegmentId = loggerRequest.SegmentReference?.SegmentId,
TraceId = loggerRequest.SegmentReference?.TraceId ?? string.Empty,
TraceSegmentId = loggerRequest.SegmentReference?.SegmentId ?? string.Empty,
//SpanId=item.Segment
},
Timestamp = loggerRequest.Date,
Service = loggerRequest.SegmentReference?.ServiceId,
ServiceInstance = loggerRequest.SegmentReference?.ServiceInstanceId,
Service = _instrumentConfig.ServiceName,
ServiceInstance = _instrumentConfig.ServiceInstanceName,
Endpoint = "",
Body = new LogDataBody()
{
Expand All @@ -99,11 +101,15 @@ public async Task ReportAsync(IReadOnlyCollection<LoggerRequest> loggerRequests,
_logger.Information($"Report {loggerRequests.Count} logs. cost: {stopwatch.Elapsed}s");
}
}
catch (Exception ex)
catch (IOException ex)
{
_logger.Error("Report trace segment fail.", ex);
_connectionManager.Failure(ex);
}
catch (Exception ex)
{
_logger.Error("Report trace segment fail.", ex);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public static IConfigurationBuilder AddSkyWalkingDefaultConfig(this IConfigurati
}

/// <summary>
/// Try append an ip to the instancename to make it more meaningful
/// Try append an ip to the instanceName to make it more meaningful
/// </summary>
/// <returns></returns>
private static string BuildDefaultServiceInstanceName()
Expand All @@ -64,9 +64,9 @@ private static string BuildDefaultServiceInstanceName()
try
{
var hostName = Dns.GetHostName();
var ipAddress = Dns.GetHostAddresses(hostName)
.Where(x => x.AddressFamily == AddressFamily.InterNetwork)
.First().ToString();
var ipAddress = Dns
.GetHostAddresses(hostName)
.First(x => x.AddressFamily == AddressFamily.InterNetwork).ToString();

return $"{ipAddress}@{guid}";
}
Expand Down