Skip to content

Refactor logging +semver:minor #182

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

Merged
merged 4 commits into from
Oct 12, 2019
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
43 changes: 41 additions & 2 deletions sample/SampleServer/Program.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using OmniSharp.Extensions.LanguageServer;
using OmniSharp.Extensions.LanguageServer.Protocol.Server;
using OmniSharp.Extensions.LanguageServer.Server;
using Serilog;

namespace SampleServer
{
Expand All @@ -22,19 +24,56 @@ static async Task MainAsync(string[] args)
// await Task.Delay(100);
// }

Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.File("log.txt", rollingInterval: RollingInterval.Day)
.CreateLogger();

Log.Logger.Information("This only goes file...");

var server = await LanguageServer.From(options =>
options
.WithInput(Console.OpenStandardInput())
.WithOutput(Console.OpenStandardOutput())
.WithLoggerFactory(new LoggerFactory())
.ConfigureLogging(x => x.AddSerilog())
.AddDefaultLoggingProvider()
.WithMinimumLogLevel(LogLevel.Trace)
.WithHandler<TextDocumentHandler>()
.WithHandler<DidChangeWatchedFilesHandler>()
.WithHandler<FoldingRangeHandler>()
.WithServices(services => {
services.AddSingleton<Foo>(provider => {
var loggerFactory = provider.GetService<ILoggerFactory>();
var logger = loggerFactory.CreateLogger<Foo>();

logger.LogInformation("Configuring");

return new Foo(logger);
});
}).OnInitialize((s, request) => {
var serviceProvider = s.Services;
var foo = serviceProvider.GetService<Foo>();

return Task.CompletedTask;
})
);

await server.WaitForExit;
}
}

internal class Foo
{
private readonly ILogger<Foo> _logger;

public Foo(ILogger<Foo> logger)
{
logger.LogInformation("inside ctor");
_logger = logger;
}

public void SayFoo()
{
_logger.LogInformation("Fooooo!");
}
}
}
4 changes: 3 additions & 1 deletion sample/SampleServer/SampleServer.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<IsPackable>false</IsPackable>
<TargetFramework>netcoreapp2.0</TargetFramework>
<TargetFramework>netcoreapp2.1</TargetFramework>
<RuntimeIdentifier>win7-x64</RuntimeIdentifier>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="../../src/Server/Server.csproj" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="2.0.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="3.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="4.1.0-dev-00850" />
</ItemGroup>

</Project>
18 changes: 7 additions & 11 deletions sample/SampleServer/TextDocumentHandler.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using OmniSharp.Extensions.Embedded.MediatR;
using OmniSharp.Extensions.LanguageServer;
using OmniSharp.Extensions.LanguageServer.Protocol;
Expand All @@ -15,7 +16,7 @@ namespace SampleServer
{
class TextDocumentHandler : ITextDocumentSyncHandler
{
private readonly OmniSharp.Extensions.LanguageServer.Protocol.Server.ILanguageServer _router;
private readonly ILogger<TextDocumentHandler> _logger;

private readonly DocumentSelector _documentSelector = new DocumentSelector(
new DocumentFilter() {
Expand All @@ -25,19 +26,17 @@ class TextDocumentHandler : ITextDocumentSyncHandler

private SynchronizationCapability _capability;

public TextDocumentHandler(OmniSharp.Extensions.LanguageServer.Protocol.Server.ILanguageServer router)
public TextDocumentHandler(ILogger<TextDocumentHandler> logger, Foo foo)
{
_router = router;
_logger = logger;
foo.SayFoo();
}

public TextDocumentSyncKind Change { get; } = TextDocumentSyncKind.Full;

public Task<Unit> Handle(DidChangeTextDocumentParams notification, CancellationToken token)
{
_router.Window.LogMessage(new LogMessageParams() {
Type = MessageType.Log,
Message = "Hello World!!!!"
});
_logger.LogInformation("Hello world!");
return Unit.Task;
}

Expand All @@ -57,10 +56,7 @@ public void SetCapability(SynchronizationCapability capability)
public async Task<Unit> Handle(DidOpenTextDocumentParams notification, CancellationToken token)
{
await Task.Yield();
_router.Window.LogMessage(new LogMessageParams() {
Type = MessageType.Log,
Message = "Hello World!!!!"
});
_logger.LogInformation("Hello world!");
return Unit.Value;
}

Expand Down
2 changes: 1 addition & 1 deletion src/JsonRpc/RequestRouterBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ public virtual async Task<ErrorResponse> RouteRequest(TDescriptor descriptor, Re

return new JsonRpc.Client.Response(request.Id, responseValue, request);
}
catch (TaskCanceledException e)
catch (TaskCanceledException)
{
_logger.LogDebug("Request {Id} was cancelled", id);
return new RequestCancelled();
Expand Down
42 changes: 24 additions & 18 deletions src/Server/LanguageServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,12 +89,11 @@ public static async Task<ILanguageServer> From(LanguageServerOptions options, Ca
/// <returns></returns>
public static ILanguageServer PreInit(LanguageServerOptions options)
{
var server = new LanguageServer(
return new LanguageServer(
options.Input,
options.Output,
options.Reciever,
options.RequestProcessIdentifier,
options.LoggerFactory,
options.Serializer,
options.Services,
options.HandlerTypes.Select(x => x.Assembly)
Expand All @@ -106,21 +105,17 @@ public static ILanguageServer PreInit(LanguageServerOptions options)
options.TextDocumentIdentifiers,
options.TextDocumentIdentifierTypes,
options.InitializeDelegates,
options.InitializedDelegates
options.InitializedDelegates,
options.LoggingBuilderAction,
options.AddDefaultLoggingProvider
);

if (options.AddDefaultLoggingProvider)
options.LoggerFactory.AddProvider(new LanguageServerLoggerProvider(server));

return server;
}

internal LanguageServer(
Stream input,
Stream output,
ILspReciever reciever,
IRequestProcessIdentifier requestProcessIdentifier,
ILoggerFactory loggerFactory,
ISerializer serializer,
IServiceCollection services,
IEnumerable<Assembly> assemblies,
Expand All @@ -131,11 +126,22 @@ internal LanguageServer(
IEnumerable<ITextDocumentIdentifier> textDocumentIdentifiers,
IEnumerable<Type> textDocumentIdentifierTypes,
IEnumerable<InitializeDelegate> initializeDelegates,
IEnumerable<InitializedDelegate> initializedDelegates)
IEnumerable<InitializedDelegate> initializedDelegates,
Action<ILoggingBuilder> loggingBuilderAction,
bool addDefaultLoggingProvider)
{
var outputHandler = new OutputHandler(output, serializer);

services.AddLogging();
services.AddLogging(builder =>
{
loggingBuilderAction(builder);

if (addDefaultLoggingProvider)
{
builder.AddProvider(new LanguageServerLoggerProvider(this));
}
});

_reciever = reciever;
_serializer = serializer;
_supportedCapabilities = new SupportedCapabilities();
Expand All @@ -153,7 +159,7 @@ internal LanguageServer(
services.AddSingleton(requestProcessIdentifier);
services.AddSingleton<OmniSharp.Extensions.JsonRpc.IReciever>(reciever);
services.AddSingleton<ILspReciever>(reciever);
services.AddSingleton(loggerFactory);

foreach (var item in handlers)
{
services.AddSingleton(item);
Expand Down Expand Up @@ -209,6 +215,12 @@ internal LanguageServer(

_exitHandler = new ServerExitHandler(_shutdownHandler);

// We need to at least create Window here in case any handler does loggin in their constructor
Document = new LanguageServerDocument(_responseRouter);
Client = new LanguageServerClient(_responseRouter);
Window = new LanguageServerWindow(_responseRouter);
Workspace = new LanguageServerWorkspace(_responseRouter);

_disposable.Add(
AddHandlers(this, _shutdownHandler, _exitHandler, new CancelRequestHandler<ILspHandlerDescriptor>(_requestRouter))
);
Expand All @@ -226,12 +238,6 @@ internal LanguageServer(
{
_disposable.Add(_collection.Add(name, handlerFunc(_serviceProvider)));
}


Document = new LanguageServerDocument(_responseRouter);
Client = new LanguageServerClient(_responseRouter);
Window = new LanguageServerWindow(_responseRouter);
Workspace = new LanguageServerWorkspace(_responseRouter);
}

public ILanguageServerDocument Document { get; }
Expand Down
3 changes: 1 addition & 2 deletions src/Server/LanguageServerOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,6 @@ public LanguageServerOptions()

public Stream Input { get; set; }
public Stream Output { get; set; }
public LogLevel MinimumLogLevel { get; set; } = LogLevel.Information;
public ILoggerFactory LoggerFactory { get; set; } = new LoggerFactory();
public ISerializer Serializer { get; set; } = Protocol.Serialization.Serializer.Instance;
public IRequestProcessIdentifier RequestProcessIdentifier { get; set; } = new RequestProcessIdentifier();
public ILspReciever Reciever { get; set; } = new LspReciever();
Expand All @@ -36,6 +34,7 @@ public LanguageServerOptions()
internal List<Type> TextDocumentIdentifierTypes { get; set; } = new List<Type>();
internal List<Assembly> HandlerAssemblies { get; set; } = new List<Assembly>();
internal bool AddDefaultLoggingProvider { get; set; }
internal Action<ILoggingBuilder> LoggingBuilderAction { get; set; } = new Action<ILoggingBuilder>(_ => { });

internal readonly List<InitializeDelegate> InitializeDelegates = new List<InitializeDelegate>();
internal readonly List<InitializedDelegate> InitializedDelegates = new List<InitializedDelegate>();
Expand Down
18 changes: 6 additions & 12 deletions src/Server/LanguageServerOptionsExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,18 +22,6 @@ public static LanguageServerOptions WithOutput(this LanguageServerOptions option
return options;
}

public static LanguageServerOptions WithMinimumLogLevel(this LanguageServerOptions options, LogLevel logLevel)
{
options.MinimumLogLevel = logLevel;
return options;
}

public static LanguageServerOptions WithLoggerFactory(this LanguageServerOptions options, ILoggerFactory loggerFactory)
{
options.LoggerFactory = loggerFactory;
return options;
}

public static LanguageServerOptions WithRequestProcessIdentifier(this LanguageServerOptions options, IRequestProcessIdentifier requestProcessIdentifier)
{
options.RequestProcessIdentifier = requestProcessIdentifier;
Expand Down Expand Up @@ -109,5 +97,11 @@ public static LanguageServerOptions OnInitialized(this LanguageServerOptions opt
options.InitializedDelegates.Add(@delegate);
return options;
}

public static LanguageServerOptions ConfigureLogging(this LanguageServerOptions options, Action<ILoggingBuilder> builderAction)
{
options.LoggingBuilderAction = builderAction;
return options;
}
}
}
14 changes: 7 additions & 7 deletions test/Lsp.Tests/LanguageServerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,10 @@ public async Task Works_With_IWorkspaceSymbolsHandler()
var serverStart = LanguageServer.From(x => x
//.WithHandler(handler)
.WithInput(process.ClientOutputStream)
.WithOutput(process.ClientInputStream)
.WithLoggerFactory(LoggerFactory)
.AddDefaultLoggingProvider()
.WithMinimumLogLevel(LogLevel.Trace),
.WithOutput(process.ClientInputStream),
//.WithLoggerFactory(LoggerFactory)
//.AddDefaultLoggingProvider()
//.WithMinimumLogLevel(LogLevel.Trace),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can probably safely delete these lines

cts.Token
);

Expand All @@ -63,9 +63,9 @@ public async Task GH141_CrashesWithEmptyInitializeParams()
var server = LanguageServer.PreInit(x => x
.WithInput(process.ClientOutputStream)
.WithOutput(process.ClientInputStream)
.WithLoggerFactory(LoggerFactory)
.AddDefaultLoggingProvider()
.WithMinimumLogLevel(LogLevel.Trace)
//.WithLoggerFactory(LoggerFactory)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can probably safely delete these lines

//.AddDefaultLoggingProvider()
//.WithMinimumLogLevel(LogLevel.Trace)
.AddHandlers(TextDocumentSyncHandlerExtensions.With(DocumentSelector.ForPattern("**/*.cs"), "csharp"))
) as IRequestHandler<InitializeParams, InitializeResult>;

Expand Down
31 changes: 11 additions & 20 deletions vscode-testextension/.vscode/tasks.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,14 @@

// A task runner that calls a custom npm script that compiles the extension.
{
"version": "0.1.0",

// we want to run npm
"command": "npm",

// the command is a shell script
"isShellCommand": true,

// show the output window only if unrecognized errors occur.
"showOutput": "silent",

// we run the custom script "compile" as defined in package.json
"args": ["run", "compile", "--loglevel", "silent"],

// The tsc compiler is started in watching mode
"isWatching": true,

// use the standard tsc in watch mode problem matcher to find compile problems in the output.
"problemMatcher": "$tsc-watch"
}
"version": "2.0.0",
"tasks": [
{
"label": "npm",
"command": "npm",
"args": ["run", "compile", "--loglevel", "silent"],
"type": "shell",
"problemMatcher": "$tsc-watch"
}
]
}
11 changes: 5 additions & 6 deletions vscode-testextension/src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,21 +20,20 @@ import { Trace } from "vscode-jsonrpc";

export function activate(context: ExtensionContext) {
// The server is implemented in node
// let serverExe = 'dotnet';
let serverExe = 'dotnet';

// let serverExe = 'D:\\Development\\Omnisharp\\csharp-language-server-protocol\\sample\\SampleServer\\bin\\Debug\\netcoreapp2.0\\win7-x64\\SampleServer.exe';
let serverExe =
"D:/Development/Omnisharp/omnisharp-roslyn/artifacts/publish/OmniSharp.Stdio.Driver/win7-x64/OmniSharp.exe";
// let serverExe = "D:/Development/Omnisharp/omnisharp-roslyn/artifacts/publish/OmniSharp.Stdio.Driver/win7-x64/OmniSharp.exe";
// The debug options for the server
// let debugOptions = { execArgv: ['-lsp', '-d' };5

// If the extension is launched in debug mode then the debug server options are used
// Otherwise the run options are used
let serverOptions: ServerOptions = {
// run: { command: serverExe, args: ['-lsp', '-d'] },
run: { command: serverExe, args: ["-lsp"] },
run: { command: serverExe, args: ["C:/src/gh/csharp-language-server-protocol/sample/SampleServer/bin/Debug/netcoreapp2.1/win7-x64/SampleServer.dll"] },
// debug: { command: serverExe, args: ['-lsp', '-d'] }
debug: { command: serverExe, args: ["-lsp"] }
debug: { command: serverExe, args: ["C:/src/gh/csharp-language-server-protocol/sample/SampleServer/bin/Debug/netcoreapp2.1/win7-x64/SampleServer.dll"] }
};

// Options to control the language client
Expand Down Expand Up @@ -65,7 +64,7 @@ export function activate(context: ExtensionContext) {
serverOptions,
clientOptions
);
// client.trace = Trace.Verbose;
client.trace = Trace.Verbose;
client.clientOptions.errorHandler;
let disposable = client.start();

Expand Down