Skip to content

Commit

Permalink
Initial version
Browse files Browse the repository at this point in the history
  • Loading branch information
augustoproiete committed Sep 9, 2018
1 parent 28d5dcf commit deadcb6
Show file tree
Hide file tree
Showing 33 changed files with 5,464 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
See: https://github.com/caioproiete/serilog-sinks-exceldnalogdisplay/releases
104 changes: 102 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,109 @@
# Serilog.Sinks.ExcelDnaLogDisplay
# Serilog.Sinks.ExcelDnaLogDisplay [![NuGet Version](http://img.shields.io/nuget/v/Serilog.Sinks.ExcelDnaLogDisplay.svg?style=flat)](https://www.nuget.org/packages/Serilog.Sinks.ExcelDnaLogDisplay/) [![License](https://img.shields.io/github/license/caioproiete/serilog-sinks-exceldnalogdisplay.svg)](LICENSE)

Writes [Serilog](https://serilog.net) events to [Excel-DNA](https://excel-dna.net) LogDisplay.
Writes [Serilog](https://serilog.net) events to [Excel-DNA](https://excel-dna.net) `LogDisplay`.

![Excel-DNA LogDisplay window screenshot](assets/exceldna-logdisplay-window.png)

### Getting started

Install the [Serilog.Sinks.ExcelDnaLogDisplay](https://www.nuget.org/packages/Serilog.Sinks.ExcelDnaLogDisplay/) package from NuGet:

```powershell
Install-Package Serilog.Sinks.ExcelDnaLogDisplay
```

To configure the sink in C# code, call `WriteTo.ExcelDnaLogDisplay()` during logger configuration:

```csharp
var log = new LoggerConfiguration()
.WriteTo.ExcelDnaLogDisplay(displayOrder: DisplayOrder.NewestFirst)
.CreateLogger();
```
### Example of an Excel-DNA add-in using Serilog with this sink

In the [sample](sample/) folder, there's an example of an Excel-DNA add-in that uses Serilog for logging to the `LogDisplay` of Excel-DNA using this sink, from different contexts, suchs as from an `ExcelRibbon` control event handler as well from an `ExcelFunction`:

[![Excel-DNA LogDisplay sample add-in ribbon screenshot](assets/sample-addin-ribbon.png)](sample/SampleAddIn/Ribbon.cs)

[![Excel-DNA LogDisplay sample add-in Excel function screenshot](assets/sample-addin-function.png)](sample/SampleAddIn/Functions.cs)

### XML `<appSettings>` configuration

To use the Excel-DNA LogDisplay sink with the [Serilog.Settings.AppSettings](https://github.com/serilog/serilog-settings-appsettings) package, first install that package if you haven't already done so:

```powershell
Install-Package Serilog.Settings.AppSettings
```

Instead of configuring the logger in code, call `ReadFrom.AppSettings()`:

```csharp
var log = new LoggerConfiguration()
.ReadFrom.AppSettings()
.CreateLogger();
```

In your Excel-DNA Add-In's `App.config`, specify the Excel-DNA LogDisplay sink assembly under the `<appSettings>` node:

```xml
<configuration>
<appSettings>
<add key="serilog:using:ExcelDnaLogDisplay" value="Serilog.Sinks.ExcelDnaLogDisplay" />
<add key="serilog:write-to:ExcelDnaLogDisplay" />
```

The parameters that can be set through the `serilog:write-to:ExcelDnaLogDisplay` keys are the method parameters accepted by the `WriteTo.ExcelDnaLogDisplay()` configuration method. This means, for example, that the `displayOrder` parameter can be set with:

```xml
<add key="serilog:write-to:ExcelDnaLogDisplay.displayOrder" value="NewestFirst" />
```

### Controlling event formatting

The Excel-DNA LogDisplay sink creates events in a fixed text format by default:

```
2018-09-07 09:02:17.148 -03:00 [INF] HTTP GET / responded 200 in 1994 ms
```

The format is controlled using an _output template_, which the Excel-DNA LogDisplay sink configuration method accepts as an `outputTemplate` parameter.

The default format above corresponds to an output template like:

```csharp
.WriteTo.ExcelDnaLogDisplay(
outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}")
```

##### JSON event formatting

To write events to the Excel-DNA LogDisplay in an alternative format such as [JSON](https://github.com/serilog/serilog-formatting-compact), pass an `ITextFormatter` as the first argument:

```csharp
// Install-Package Serilog.Formatting.Compact
.WriteTo.ExcelDnaLogDisplay(new CompactJsonFormatter())
```

### Auditing

The Excel-DNA LogDisplay sink can operate as an audit sink through `AuditTo`:

```csharp
.AuditTo.ExcelDnaLogDisplay(displayOrder: DisplayOrder.NewestFirst)
```

### Excel-DNA configuration for packing with `ExcelDnaPack`

In order for the Excel-DNA LogDisplay sink to work from an add-in that was packaged using the ExcelDnaPack utility, you need to include references to `Serilog.dll` and `Serilog.Sinks.ExcelDnaLogDisplay.dll` in the `.dna` file of the add-in:

```xml
<DnaLibrary Name="My Add-In" RuntimeVersion="v4.0">
<ExternalLibrary Path="MyAddIn.dll" ExplicitExports="false" LoadFromBytes="true" Pack="true" />

<Reference Path="Serilog.dll" Pack="true" />
<Reference Path="Serilog.Sinks.ExcelDnaLogDisplay.dll" Pack="true" />
```

---

_Copyright &copy; 2018 Caio Proiete & Contributors - Provided under the [Apache License, Version 2.0](http://apache.org/licenses/LICENSE-2.0.html)._
Binary file added assets/sample-addin-function.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added assets/sample-addin-ribbon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added assets/serilog-sinks-exceldnalogdisplay-nuget.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
154 changes: 154 additions & 0 deletions sample/SampleAddIn/AddIn.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
// Copyright 2018 Caio Proiete & Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using ExcelDna.Integration;
using ExcelDna.Integration.Extensibility;
using ExcelDna.Logging;
using ExcelDna.Registration;
using Serilog;

namespace SampleAddIn
{
public class AddIn : ExcelComAddIn, IExcelAddIn
{
private static ILogger _log = Log.Logger;

public void AutoOpen()
{
try
{
Application.ThreadException += ApplicationThreadUnhandledException;
AppDomain.CurrentDomain.UnhandledException += AppDomainUnhandledException;
TaskScheduler.UnobservedTaskException += TaskSchedulerUnobservedTaskException;
ExcelIntegration.RegisterUnhandledExceptionHandler(ExcelUnhandledException);

_log = Log.Logger = ConfigureLogging();
_log.Information("Starting sample Excel-DNA Add-In with Serilog Sink LogDisplay");

ExcelComAddInHelper.LoadComAddIn(this);

_log.Verbose("Registering functions");

ExcelRegistration.GetExcelFunctions()
.Select(UpdateFunctionAttributes)
.RegisterFunctions();

_log.Information("Sample Excel-DNA Add-In with Serilog Sink LogDisplay started");
}
catch (Exception ex)
{
ProcessUnhandledException(ex);
}
}

public void AutoClose()
{
// Do nothing
}

public override void OnDisconnection(ext_DisconnectMode disconnectMode, ref Array custom)
{
try
{
base.OnDisconnection(disconnectMode, ref custom);

_log.Information("Stopping sample Excel-DNA Add-In with Serilog Sink LogDisplay");
}
catch (Exception ex)
{
ProcessUnhandledException(ex);
}
finally
{
_log.Information("Sample Excel-DNA Add-In with Serilog Sink LogDisplay stopped");

Log.CloseAndFlush();
}
}

public static void ProcessUnhandledException(Exception ex, string message = null, [CallerMemberName] string caller = null)
{
try
{
_log.Error(ex, message ?? $"Unhandled exception on {caller}");
}
catch (Exception lex)
{
try
{
Serilog.Debugging.SelfLog.WriteLine(lex.ToString());
}
catch
{
// Do nothing...
}
}

if (ex.InnerException != null)
{
ProcessUnhandledException(ex.InnerException, message, caller);
return;
}

#if DEBUG
MessageBox.Show(ex.ToString(), "Unexpected Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
#else
const string errorMessage = "An unexpected error ocurred. Please try again in a few minutes, and if the error persists, contact support";
MessageBox.Show(errorMessage, "Unexpected Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
#endif
}

private static ILogger ConfigureLogging()
{
return new LoggerConfiguration()
.MinimumLevel.Verbose()
.WriteTo.ExcelDnaLogDisplay(displayOrder: DisplayOrder.NewestFirst)
.CreateLogger();
}

private static ExcelFunctionRegistration UpdateFunctionAttributes(ExcelFunctionRegistration excelFunction)
{
excelFunction.FunctionAttribute.Name = excelFunction.FunctionAttribute.Name.ToUpperInvariant();
return excelFunction;
}

private static void ApplicationThreadUnhandledException(object sender, ThreadExceptionEventArgs e)
{
ProcessUnhandledException(e.Exception);
}

private static void TaskSchedulerUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
{
ProcessUnhandledException(e.Exception);
e.SetObserved();
}

private static void AppDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
ProcessUnhandledException((Exception)e.ExceptionObject);
}

private static object ExcelUnhandledException(object ex)
{
ProcessUnhandledException((Exception)ex);
return ex;
}
}
}
6 changes: 6 additions & 0 deletions sample/SampleAddIn/App.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
</configuration>
59 changes: 59 additions & 0 deletions sample/SampleAddIn/Functions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// Copyright 2018 Caio Proiete & Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using ExcelDna.Integration;
using Serilog;

namespace SampleAddIn
{
public static class Functions
{
private static readonly ILogger _log = Log.Logger.ForContext(typeof(Functions));

[ExcelFunction(Category = "Serilog", Description = "Writes a `Verbose` message to the LogDisplay via Serilog")]
public static string LogVerbose(string message)
{
_log.Verbose(message);
return $"'[VRB] {message}' written to the log";
}

[ExcelFunction(Category = "Serilog", Description = "Writes a `Debug` message to the LogDisplay via Serilog")]
public static string LogDebug(string message)
{
_log.Debug(message);
return $"'[DBG] {message}' written to the log";
}

[ExcelFunction(Category = "Serilog", Description = "Writes an `Information` message to the LogDisplay via Serilog")]
public static string LogInformation(string message)
{
_log.Information(message);
return $"'[INF] {message}' written to the log";
}

[ExcelFunction(Category = "Serilog", Description = "Writes a `Warning` message to the LogDisplay via Serilog")]
public static string LogWarning(string message)
{
_log.Warning(message);
return $"'[WRN] {message}' written to the log";
}

[ExcelFunction(Category = "Serilog", Description = "Writes an `Error` message to the LogDisplay via Serilog")]
public static string LogError(string message)
{
_log.Error(message);
return $"'[ERR] {message}' written to the log";
}
}
}
Loading

0 comments on commit deadcb6

Please # to comment.