├── .gitattributes ├── .gitignore ├── Build.ps1 ├── CHANGES.md ├── LICENSE ├── README.md ├── assets ├── CommonAssemblyInfo.cs └── Serilog.snk ├── serilog-sinks-signalr.sln └── src └── Serilog.Sinks.SignalR ├── LoggerConfigurationSignalRExtensions.cs ├── Properties └── AssemblyInfo.cs ├── Serilog.Sinks.SignalR.csproj ├── Serilog.Sinks.SignalR.nuspec ├── Sinks └── SignalR │ ├── Data │ └── LogEvent.cs │ ├── SignalRClientSink.cs │ ├── SignalRPropertyFormatter.cs │ └── SignalRSink.cs ├── app.config └── packages.config /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | 3 | * text=auto 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.sln.docstates 8 | 9 | # Build results 10 | [Dd]ebug/ 11 | [Dd]ebugPublic/ 12 | [Rr]elease/ 13 | [Rr]eleases/ 14 | x64/ 15 | x86/ 16 | build/ 17 | bld/ 18 | [Bb]in/ 19 | [Oo]bj/ 20 | 21 | # Roslyn cache directories 22 | *.ide/ 23 | 24 | # MSTest test Results 25 | [Tt]est[Rr]esult*/ 26 | [Bb]uild[Ll]og.* 27 | 28 | #NUNIT 29 | *.VisualState.xml 30 | TestResult.xml 31 | 32 | # Build Results of an ATL Project 33 | [Dd]ebugPS/ 34 | [Rr]eleasePS/ 35 | dlldata.c 36 | 37 | *_i.c 38 | *_p.c 39 | *_i.h 40 | *.ilk 41 | *.meta 42 | *.obj 43 | *.pch 44 | *.pdb 45 | *.pgc 46 | *.pgd 47 | *.rsp 48 | *.sbr 49 | *.tlb 50 | *.tli 51 | *.tlh 52 | *.tmp 53 | *.tmp_proj 54 | *.log 55 | *.vspscc 56 | *.vssscc 57 | .builds 58 | *.pidb 59 | *.svclog 60 | *.scc 61 | 62 | # Chutzpah Test files 63 | _Chutzpah* 64 | 65 | # Visual C++ cache files 66 | ipch/ 67 | *.aps 68 | *.ncb 69 | *.opensdf 70 | *.sdf 71 | *.cachefile 72 | 73 | # Visual Studio profiler 74 | *.psess 75 | *.vsp 76 | *.vspx 77 | 78 | # TFS 2012 Local Workspace 79 | $tf/ 80 | 81 | # Guidance Automation Toolkit 82 | *.gpState 83 | 84 | # ReSharper is a .NET coding add-in 85 | _ReSharper*/ 86 | *.[Rr]e[Ss]harper 87 | *.DotSettings.user 88 | 89 | # JustCode is a .NET coding addin-in 90 | .JustCode 91 | 92 | # TeamCity is a build add-in 93 | _TeamCity* 94 | 95 | # DotCover is a Code Coverage Tool 96 | *.dotCover 97 | 98 | # NCrunch 99 | _NCrunch_* 100 | .*crunch*.local.xml 101 | 102 | # MightyMoose 103 | *.mm.* 104 | AutoTest.Net/ 105 | 106 | # Web workbench (sass) 107 | .sass-cache/ 108 | 109 | # Installshield output folder 110 | [Ee]xpress/ 111 | 112 | # DocProject is a documentation generator add-in 113 | DocProject/buildhelp/ 114 | DocProject/Help/*.HxT 115 | DocProject/Help/*.HxC 116 | DocProject/Help/*.hhc 117 | DocProject/Help/*.hhk 118 | DocProject/Help/*.hhp 119 | DocProject/Help/Html2 120 | DocProject/Help/html 121 | 122 | # Click-Once directory 123 | publish/ 124 | 125 | # Publish Web Output 126 | *.[Pp]ublish.xml 127 | *.azurePubxml 128 | # TODO: Comment the next line if you want to checkin your web deploy settings 129 | # but database connection strings (with potential passwords) will be unencrypted 130 | *.pubxml 131 | *.publishproj 132 | 133 | # NuGet Packages 134 | *.nupkg 135 | # The packages folder can be ignored because of Package Restore 136 | **/packages/* 137 | # except build/, which is used as an MSBuild target. 138 | !**/packages/build/ 139 | # If using the old MSBuild-Integrated Package Restore, uncomment this: 140 | #!**/packages/repositories.config 141 | 142 | # Windows Azure Build Output 143 | csx/ 144 | *.build.csdef 145 | 146 | # Windows Store app package directory 147 | AppPackages/ 148 | 149 | # Others 150 | sql/ 151 | *.Cache 152 | ClientBin/ 153 | [Ss]tyle[Cc]op.* 154 | ~$* 155 | *~ 156 | *.dbmdl 157 | *.dbproj.schemaview 158 | *.pfx 159 | *.publishsettings 160 | node_modules/ 161 | 162 | # RIA/Silverlight projects 163 | Generated_Code/ 164 | 165 | # Backup & report files from converting an old project file 166 | # to a newer Visual Studio version. Backup files are not needed, 167 | # because we have git ;-) 168 | _UpgradeReport_Files/ 169 | Backup*/ 170 | UpgradeLog*.XML 171 | UpgradeLog*.htm 172 | 173 | # SQL Server files 174 | *.mdf 175 | *.ldf 176 | 177 | # Business Intelligence projects 178 | *.rdl.data 179 | *.bim.layout 180 | *.bim_*.settings 181 | 182 | # Microsoft Fakes 183 | FakesAssemblies/ 184 | -------------------------------------------------------------------------------- /Build.ps1: -------------------------------------------------------------------------------- 1 | param( 2 | [String] $majorMinor = "0.0", # 2.0 3 | [String] $patch = "0", # $env:APPVEYOR_BUILD_VERSION 4 | [String] $customLogger = "", # C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll 5 | [Switch] $notouch, 6 | [String] $sln # e.g serilog-sink-name 7 | ) 8 | 9 | function Set-AssemblyVersions($informational, $assembly) 10 | { 11 | (Get-Content assets/CommonAssemblyInfo.cs) | 12 | ForEach-Object { $_ -replace """1.0.0.0""", """$assembly""" } | 13 | ForEach-Object { $_ -replace """1.0.0""", """$informational""" } | 14 | ForEach-Object { $_ -replace """1.1.1.1""", """$($informational).0""" } | 15 | Set-Content assets/CommonAssemblyInfo.cs 16 | } 17 | 18 | function Install-NuGetPackages($solution) 19 | { 20 | nuget restore $solution 21 | } 22 | 23 | function Invoke-MSBuild($solution, $customLogger) 24 | { 25 | if ($customLogger) 26 | { 27 | msbuild "$solution" /verbosity:minimal /p:Configuration=Release /logger:"$customLogger" 28 | } 29 | else 30 | { 31 | msbuild "$solution" /verbosity:minimal /p:Configuration=Release 32 | } 33 | } 34 | 35 | function Invoke-NuGetPackProj($csproj) 36 | { 37 | nuget pack -Prop Configuration=Release -Symbols $csproj 38 | } 39 | 40 | function Invoke-NuGetPackSpec($nuspec, $version) 41 | { 42 | nuget pack $nuspec -Version $version -OutputDirectory ..\..\ 43 | } 44 | 45 | function Invoke-NuGetPack($version) 46 | { 47 | ls src/**/*.csproj | 48 | Where-Object { -not ($_.Name -like "*net40*") } | 49 | ForEach-Object { Invoke-NuGetPackProj $_ } 50 | } 51 | 52 | function Invoke-Build($majorMinor, $patch, $customLogger, $notouch, $sln) 53 | { 54 | $package="$majorMinor.$patch" 55 | $slnfile = "$sln.sln" 56 | 57 | Write-Output "$sln $package" 58 | 59 | if (-not $notouch) 60 | { 61 | $assembly = "$majorMinor.0.0" 62 | 63 | Write-Output "Assembly version will be set to $assembly" 64 | Set-AssemblyVersions $package $assembly 65 | } 66 | 67 | Install-NuGetPackages $slnfile 68 | 69 | Invoke-MSBuild $slnfile $customLogger 70 | 71 | Invoke-NuGetPack $package 72 | } 73 | 74 | $ErrorActionPreference = "Stop" 75 | 76 | if (-not $sln) 77 | { 78 | $slnfull = ls *.sln | 79 | Where-Object { -not ($_.Name -like "*net40*") } | 80 | Select -first 1 81 | 82 | $sln = $slnfull.BaseName 83 | } 84 | 85 | Invoke-Build $majorMinor $patch $customLogger $notouch $sln 86 | -------------------------------------------------------------------------------- /CHANGES.md: -------------------------------------------------------------------------------- 1 | 1.5 2 | * Moved from serilog/serilog 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # serilog-sinks-signalr 2 | 3 | [![Build status](https://ci.appveyor.com/api/projects/status/292m45fa26x5iyfs/branch/master?svg=true)](https://ci.appveyor.com/project/serilog/serilog-sinks-signalr/branch/master) 4 | 5 | A Serilog sink that writes events to a SignalR Hub 6 | 7 | ## Configuration from hub application 8 | 9 | From within the SignalR server application with a hub named MyHub: 10 | 11 | ```csharp 12 | var hubContext = GlobalHost.ConnectionManager.GetHubContext(); 13 | 14 | Log.Logger = new LoggerConfiguration() 15 | .MinimumLevel.Verbose() 16 | .WriteTo.SignalR(hubContext, 17 | Serilog.Events.LogEventLevel.Information, 18 | groupNames: new[] { "CustomGroup"}, // default is null 19 | userIds: new[] { "JaneD1234" }, // default is null 20 | excludedConnectionIds: new[] { "12345", "678910" }) // default is null 21 | .CreateLogger(); 22 | ``` 23 | 24 | ## Configuration from other clients 25 | 26 | From any client application with a hub hosted at `http://localhost:8080` and a hub implemented named `MyHub`: 27 | 28 | ```csharp 29 | Log.Logger = new LoggerConfiguration() 30 | .MinimumLevel.Verbose() 31 | .WriteTo.SignalRClient("http://localhost:8080", 32 | Serilog.Events.LogEventLevel.Information, 33 | hub: "MyHub" // default is LogHub 34 | groupNames: new[] { "CustomGroup"}, // default is null 35 | userIds: new[] { "JaneD1234" }) // default is null 36 | .CreateLogger(); 37 | ``` 38 | 39 | ### SignalR Server 40 | Create a hub class with any name that ends in `Hub` or use the default name `LogHub`. Then create a method named `receiveLogEvent`, which is capable of accepting all data from the sink. 41 | ```csharp 42 | public class MyHub : Hub 43 | { 44 | public void receiveLogEvent(string[] groups, string[] userIds, Serilog.Sinks.SignalR.Data.LogEvent logEvent) 45 | { 46 | // send to all clients 47 | Clients.All.sendLogEvent(logEvent); 48 | // just the specified groups 49 | Clients.Groups(groups).sendLogEvent(logEvent); 50 | // just the specified users 51 | Clients.Users(users).sendLogEvent(logEvent); 52 | } 53 | } 54 | ``` 55 | 56 | ## Receiving the log event 57 | Set up a SignalR client and subscribe to the `sendLogEvent` method. 58 | 59 | ```csharp 60 | var connection = new HubConnection("http://localhost:8080"); 61 | var hubProxy = connection.CreateHubProxy("MyHub"); 62 | 63 | hubProxy.On("sendLogEvent", (logEvent) => 64 | { 65 | Console.WriteLine(logEvent.RenderedMessage); 66 | }); 67 | ``` -------------------------------------------------------------------------------- /assets/CommonAssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | 3 | [assembly: AssemblyVersion("1.0.0.0")] 4 | [assembly: AssemblyFileVersion("1.1.1.1")] 5 | [assembly: AssemblyInformationalVersion("1.0.0")] 6 | -------------------------------------------------------------------------------- /assets/Serilog.snk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/serilog-archive/serilog-sinks-signalr/7ea582e93d6611f0202a9d3e55e485c9f66a52aa/assets/Serilog.snk -------------------------------------------------------------------------------- /serilog-sinks-signalr.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 2013 4 | VisualStudioVersion = 12.0.31101.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Serilog.Sinks.SignalR", "src\Serilog.Sinks.SignalR\Serilog.Sinks.SignalR.csproj", "{0D51B456-A1B0-4048-9E90-E98CEB95E976}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {0D51B456-A1B0-4048-9E90-E98CEB95E976}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {0D51B456-A1B0-4048-9E90-E98CEB95E976}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {0D51B456-A1B0-4048-9E90-E98CEB95E976}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {0D51B456-A1B0-4048-9E90-E98CEB95E976}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | EndGlobal 23 | -------------------------------------------------------------------------------- /src/Serilog.Sinks.SignalR/LoggerConfigurationSignalRExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.AspNet.SignalR; 3 | using Serilog.Configuration; 4 | using Serilog.Events; 5 | using Serilog.Sinks.SignalR; 6 | 7 | // Copyright 2014 Serilog Contributors 8 | // 9 | // Licensed under the Apache License, Version 2.0 (the "License"); 10 | // you may not use this file except in compliance with the License. 11 | // You may obtain a copy of the License at 12 | // 13 | // http://www.apache.org/licenses/LICENSE-2.0 14 | // 15 | // Unless required by applicable law or agreed to in writing, software 16 | // distributed under the License is distributed on an "AS IS" BASIS, 17 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | // See the License for the specific language governing permissions and 19 | // limitations under the License. 20 | 21 | namespace Serilog 22 | { 23 | /// 24 | /// Adds the WriteTo.SignalR() extension method to . 25 | /// 26 | public static class LoggerConfigurationSignalRExtensions 27 | { 28 | /// 29 | /// Adds a sink that writes log events as documents to a SignalR hub. 30 | /// 31 | /// The logger configuration. 32 | /// The hub context. 33 | /// The minimum log event level required in order to write an event to the sink. 34 | /// The maximum number of events to post in a single batch. 35 | /// The time to wait between checking for event batches. 36 | /// Supplies culture-specific formatting information, or null. 37 | /// Names of the Signalr groups you are broadcasting the log event to. Default is All Groups. 38 | /// ID's of the Signalr Users you are broadcasting the log event to. Default is All Users. 39 | /// Signalr connection ID's to exclude from broadcast. 40 | /// Logger configuration, allowing configuration to continue. 41 | /// A required parameter is null. 42 | public static LoggerConfiguration SignalR( 43 | this LoggerSinkConfiguration loggerConfiguration, 44 | IHubContext context, 45 | LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum, 46 | int batchPostingLimit = SignalRSink.DefaultBatchPostingLimit, 47 | TimeSpan? period = null, 48 | IFormatProvider formatProvider = null, 49 | string[] groupNames = null, 50 | string[] userIds = null, 51 | string[] excludedConnectionIds = null) 52 | { 53 | if (loggerConfiguration == null) throw new ArgumentNullException(nameof(loggerConfiguration)); 54 | if (context == null) throw new ArgumentNullException(nameof(context)); 55 | 56 | var defaultedPeriod = period ?? SignalRSink.DefaultPeriod; 57 | return loggerConfiguration.Sink( 58 | new SignalRSink(context, batchPostingLimit, defaultedPeriod, formatProvider, groupNames, userIds, excludedConnectionIds), 59 | restrictedToMinimumLevel); 60 | } 61 | 62 | /// 63 | /// Adds a sink that writes log events as documents to a SignalR hub. 64 | /// 65 | /// The logger configuration. 66 | /// The url of the hub. http://localhost:8080. 67 | /// The minimum log event level required in order to write an event to the sink. 68 | /// The maximum number of events to post in a single batch. 69 | /// The time to wait between checking for event batches. 70 | /// Supplies culture-specific formatting information, or null. 71 | /// The name of the Signalr hub class. Default is LogHub 72 | /// Names of the Signalr groups you are broadcasting the log event to. Default is All Groups. 73 | /// ID's of the Signalr Users you are broadcasting the log event to. Default is All Users. 74 | /// Logger configuration, allowing configuration to continue. 75 | /// A required parameter is null. 76 | public static LoggerConfiguration SignalRClient( 77 | this LoggerSinkConfiguration loggerConfiguration, 78 | string url, 79 | LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum, 80 | int batchPostingLimit = SignalRSink.DefaultBatchPostingLimit, 81 | TimeSpan? period = null, 82 | IFormatProvider formatProvider = null, 83 | string hub = "LogHub", 84 | string[] groupNames = null, 85 | string[] userIds = null) 86 | { 87 | if (loggerConfiguration == null) throw new ArgumentNullException(nameof(loggerConfiguration)); 88 | if (url == null) throw new ArgumentNullException(nameof(url)); 89 | 90 | var defaultedPeriod = period ?? SignalRSink.DefaultPeriod; 91 | return loggerConfiguration.Sink( 92 | new SignalRClientSink(url, batchPostingLimit, defaultedPeriod, formatProvider, hub, groupNames, userIds), 93 | restrictedToMinimumLevel); 94 | } 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /src/Serilog.Sinks.SignalR/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | 4 | [assembly: AssemblyTitle("Serilog.Sinks.SignalR")] 5 | [assembly: AssemblyDescription("Serilog sink for SignalR")] 6 | [assembly: AssemblyCopyright("Copyright © Serilog Contributors 2013")] 7 | 8 | [assembly: InternalsVisibleTo("Serilog.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100fb8d13fd344a1c" + 9 | "6fe0fe83ef33c1080bf30690765bc6eb0df26ebfdf8f21670c64265b30db09f73a0dea5b3db4c9" + 10 | "d18dbf6d5a25af5ce9016f281014d79dc3b4201ac646c451830fc7e61a2dfd633d34c39f87b818" + 11 | "94191652df5ac63cc40c77f3542f702bda692e6e8a9158353df189007a49da0f3cfd55eb250066" + 12 | "b19485ec")] -------------------------------------------------------------------------------- /src/Serilog.Sinks.SignalR/Serilog.Sinks.SignalR.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {0D51B456-A1B0-4048-9E90-E98CEB95E976} 8 | Library 9 | Properties 10 | Serilog 11 | Serilog.Sinks.SignalR 12 | v4.6 13 | 512 14 | ..\ 15 | 16 | 17 | 18 | true 19 | full 20 | false 21 | bin\Debug\ 22 | DEBUG;TRACE 23 | prompt 24 | 4 25 | true 26 | bin\Debug\Serilog.Sinks.SignalR.XML 27 | 28 | 29 | pdbonly 30 | true 31 | bin\Release\ 32 | TRACE 33 | prompt 34 | 4 35 | true 36 | bin\Release\Serilog.Sinks.SignalR.XML 37 | 38 | 39 | true 40 | 41 | 42 | ..\..\assets\Serilog.snk 43 | 44 | 45 | 46 | ..\..\packages\Microsoft.AspNet.SignalR.Client.2.2.1\lib\net45\Microsoft.AspNet.SignalR.Client.dll 47 | 48 | 49 | ..\..\packages\Microsoft.AspNet.SignalR.Core.2.2.1\lib\net45\Microsoft.AspNet.SignalR.Core.dll 50 | 51 | 52 | ..\..\packages\Microsoft.Owin.3.0.1\lib\net45\Microsoft.Owin.dll 53 | 54 | 55 | ..\..\packages\Microsoft.Owin.Security.3.0.1\lib\net45\Microsoft.Owin.Security.dll 56 | 57 | 58 | ..\..\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll 59 | 60 | 61 | ..\..\packages\Owin.1.0\lib\net40\Owin.dll 62 | 63 | 64 | ..\..\packages\Serilog.2.3.0\lib\net46\Serilog.dll 65 | 66 | 67 | ..\..\packages\Serilog.Sinks.PeriodicBatching.2.1.0\lib\net45\Serilog.Sinks.PeriodicBatching.dll 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | Properties\CommonAssemblyInfo.cs 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | Serilog.snk 91 | 92 | 93 | 94 | 95 | Designer 96 | 97 | 98 | 99 | 100 | -------------------------------------------------------------------------------- /src/Serilog.Sinks.SignalR/Serilog.Sinks.SignalR.nuspec: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Serilog.Sinks.SignalR 5 | $version$ 6 | Steve Rasch 7 | Serilog event sink that writes to a SignalR-Hub. 8 | en-US 9 | http://serilog.net 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | http://serilog.net/images/serilog-sink-nuget.png 12 | serilog logging signalr 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /src/Serilog.Sinks.SignalR/Sinks/SignalR/Data/LogEvent.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2014 Serilog Contributors 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System; 16 | using System.Collections.Generic; 17 | using Serilog.Events; 18 | 19 | namespace Serilog.Sinks.SignalR.Data 20 | { 21 | /// 22 | /// A wrapper class for that is sent as a message to SignalR clients. 23 | /// 24 | public class LogEvent 25 | { 26 | /// 27 | /// Construct a new . 28 | /// 29 | public LogEvent() 30 | { 31 | } 32 | 33 | /// 34 | /// Construct a new . 35 | /// 36 | public LogEvent(Events.LogEvent logEvent, string renderedMessage) 37 | { 38 | Timestamp = logEvent.Timestamp; 39 | Exception = logEvent.Exception; 40 | MessageTemplate = logEvent.MessageTemplate.Text; 41 | Level = logEvent.Level; 42 | RenderedMessage = renderedMessage; 43 | Properties = new Dictionary(); 44 | foreach (var pair in logEvent.Properties) 45 | { 46 | Properties.Add(pair.Key, SignalRPropertyFormatter.Simplify(pair.Value)); 47 | } 48 | } 49 | 50 | /// 51 | /// The time at which the event occurred. 52 | /// 53 | public DateTimeOffset Timestamp { get; set; } 54 | 55 | /// 56 | /// The template that was used for the log message. 57 | /// 58 | public string MessageTemplate { get; set; } 59 | 60 | /// 61 | /// The level of the log. 62 | /// 63 | public LogEventLevel Level { get; set; } 64 | 65 | /// 66 | /// A string representation of the exception that was attached to the log (if any). 67 | /// 68 | public Exception Exception { get; set; } 69 | 70 | /// 71 | /// The rendered log message. 72 | /// 73 | public string RenderedMessage { get; set; } 74 | 75 | /// 76 | /// Properties associated with the event, including those presented in . 77 | /// 78 | public IDictionary Properties { get; set; } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/Serilog.Sinks.SignalR/Sinks/SignalR/SignalRClientSink.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2014 Serilog Contributors 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System; 16 | using System.Collections.Generic; 17 | using Microsoft.AspNet.SignalR.Client; 18 | using Serilog.Sinks.PeriodicBatching; 19 | using LogEvent = Serilog.Sinks.SignalR.Data.LogEvent; 20 | 21 | namespace Serilog.Sinks.SignalR 22 | { 23 | /// 24 | /// Writes log events as messages to a SignalR hub. 25 | /// 26 | public class SignalRClientSink : PeriodicBatchingSink 27 | { 28 | readonly IFormatProvider _formatProvider; 29 | readonly HubConnection _connection; 30 | readonly IHubProxy _hubProxy; 31 | readonly string[] _groupNames; 32 | readonly string[] _userIds; 33 | 34 | /// 35 | /// A reasonable default for the number of events posted in 36 | /// each batch. 37 | /// 38 | public const int DefaultBatchPostingLimit = 5; 39 | 40 | /// 41 | /// A reasonable default time to wait between checking for event batches. 42 | /// 43 | public static readonly TimeSpan DefaultPeriod = TimeSpan.FromSeconds(2); 44 | 45 | /// 46 | /// Construct a sink posting to the specified database. 47 | /// 48 | /// The url of the hub. http://localhost:8080. 49 | /// The maximum number of events to post in a single batch. 50 | /// The time to wait between checking for event batches. 51 | /// Supplies culture-specific formatting information, or null. 52 | /// The name of the Signalr hub class. Default is LogHub 53 | /// Names of the Signalr groups you are broadcasting the log event to. Default is All Groups. 54 | /// ID's of the Signalr Users you are broadcasting the log event to. Default is All Users. 55 | public SignalRClientSink(string url, int batchPostingLimit, TimeSpan period, IFormatProvider formatProvider, string hub = "LogHub", string[] groupNames = null, string[] userIds = null) 56 | : base(batchPostingLimit, period) 57 | { 58 | if (url == null) throw new ArgumentNullException(nameof(url)); 59 | 60 | _formatProvider = formatProvider; 61 | _groupNames = groupNames ?? Array.Empty(); 62 | _userIds = userIds ?? Array.Empty(); 63 | 64 | _connection = new HubConnection(url); 65 | _hubProxy = _connection.CreateHubProxy(hub); 66 | // does not block, but will take some time to initialize 67 | _connection.Start(); 68 | } 69 | 70 | /// 71 | /// Emit a batch of log events, running asynchronously. 72 | /// 73 | /// The events to emit. 74 | /// Override either or , 75 | /// not both. 76 | protected override void EmitBatch(IEnumerable events) 77 | { 78 | // This sink doesn't use batching to send events, instead only using 79 | // PeriodicBatchingSink to manage the worker thread; requires some consideration. 80 | 81 | foreach (var logEvent in events) 82 | { 83 | // send the log message to the hub 84 | switch (_connection.State) 85 | { 86 | case ConnectionState.Connected: 87 | _hubProxy.Invoke("receiveLogEvent", _groupNames, _userIds, new LogEvent(logEvent, logEvent.RenderMessage(_formatProvider))); 88 | break; 89 | case ConnectionState.Disconnected: 90 | // attempt to restart the connection 91 | _connection.Start(); 92 | break; 93 | } 94 | } 95 | } 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/Serilog.Sinks.SignalR/Sinks/SignalR/SignalRPropertyFormatter.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2014 Serilog Contributors 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System; 16 | using System.Collections.Generic; 17 | using System.Linq; 18 | using Serilog.Events; 19 | 20 | namespace Serilog.Sinks.SignalR 21 | { 22 | /// 23 | /// Converts values into simple scalars, 24 | /// dictionaries and lists so that they can be persisted in RavenDB. 25 | /// 26 | public static class SignalRPropertyFormatter 27 | { 28 | static readonly HashSet SignalRSpecialScalars = new HashSet 29 | { 30 | typeof(bool), 31 | typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), 32 | typeof(long), typeof(ulong), typeof(float), typeof(double), typeof(decimal), 33 | typeof(byte[]) 34 | }; 35 | 36 | /// 37 | /// Simplify the object so as to make handling the serialized 38 | /// representation easier. 39 | /// 40 | /// The value to simplify (possibly null). 41 | /// A simplified representation. 42 | public static object Simplify(LogEventPropertyValue value) 43 | { 44 | var scalar = value as ScalarValue; 45 | if (scalar != null) 46 | return SimplifyScalar(scalar.Value); 47 | 48 | var dict = value as DictionaryValue; 49 | if (dict != null) 50 | return dict 51 | .Elements 52 | .ToDictionary(kv => SimplifyScalar(kv.Key), kv => Simplify(kv.Value)); 53 | 54 | var seq = value as SequenceValue; 55 | if (seq != null) 56 | return seq.Elements.Select(Simplify).ToArray(); 57 | 58 | var str = value as StructureValue; 59 | if (str != null) 60 | { 61 | var props = str.Properties.ToDictionary(p => p.Name, p => Simplify(p.Value)); 62 | if (str.TypeTag != null) 63 | props["$typeTag"] = str.TypeTag; 64 | return props; 65 | } 66 | 67 | return null; 68 | } 69 | 70 | static object SimplifyScalar(object value) 71 | { 72 | if (value == null) 73 | return null; 74 | 75 | var valueType = value.GetType(); 76 | if (SignalRSpecialScalars.Contains(valueType)) 77 | return value; 78 | 79 | return value.ToString(); 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/Serilog.Sinks.SignalR/Sinks/SignalR/SignalRSink.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2014 Serilog Contributors 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System; 16 | using System.Collections.Generic; 17 | using Microsoft.AspNet.SignalR; 18 | using Serilog.Sinks.PeriodicBatching; 19 | using LogEvent = Serilog.Sinks.SignalR.Data.LogEvent; 20 | 21 | namespace Serilog.Sinks.SignalR 22 | { 23 | /// 24 | /// Writes log events as messages to a SignalR hub. 25 | /// 26 | public class SignalRSink : PeriodicBatchingSink 27 | { 28 | readonly IFormatProvider _formatProvider; 29 | readonly IHubContext _context; 30 | readonly string[] _groupNames; 31 | readonly string[] _userIds; 32 | readonly string[] _excludedConnectionIds; 33 | 34 | /// 35 | /// A reasonable default for the number of events posted in 36 | /// each batch. 37 | /// 38 | public const int DefaultBatchPostingLimit = 5; 39 | 40 | /// 41 | /// A reasonable default time to wait between checking for event batches. 42 | /// 43 | public static readonly TimeSpan DefaultPeriod = TimeSpan.FromSeconds(2); 44 | 45 | /// 46 | /// Construct a sink posting to the specified database. 47 | /// 48 | /// The hub context. 49 | /// The maximum number of events to post in a single batch. 50 | /// The time to wait between checking for event batches. 51 | /// Supplies culture-specific formatting information, or null. 52 | /// Name of the Signalr group you are broadcasting the log event to. Default is All connections. 53 | /// ID's of the Signalr Users you are broadcasting the log event to. Default is All Users. 54 | /// Signalr connection ID's to exclude from broadcast. 55 | public SignalRSink(IHubContext context, int batchPostingLimit, TimeSpan period, IFormatProvider formatProvider, string[] groupNames = null, string[] userIds = null, string[] excludedConnectionIds = null) 56 | : base(batchPostingLimit, period) 57 | { 58 | if (context == null) 59 | throw new ArgumentNullException(nameof(context)); 60 | _formatProvider = formatProvider; 61 | _context = context; 62 | _groupNames = groupNames; 63 | _userIds = userIds; 64 | _excludedConnectionIds = excludedConnectionIds ?? Array.Empty(); 65 | } 66 | 67 | /// 68 | /// Emit a batch of log events, running asynchronously. 69 | /// 70 | /// The events to emit. 71 | /// Override either or , 72 | /// not both. 73 | protected override void EmitBatch(IEnumerable events) 74 | { 75 | // This sink doesn't use batching to send events, instead only using 76 | // PeriodicBatchingSink to manage the worker thread; requires some consideration. 77 | 78 | foreach (var logEvent in events) 79 | { 80 | dynamic target; 81 | // target the specified clients while opting out the excluded connections 82 | if (_groupNames != null && _groupNames != Array.Empty()) 83 | target = _context.Clients.Groups(_groupNames, _excludedConnectionIds); 84 | else if (_userIds != null && _userIds != Array.Empty()) 85 | target = _context.Clients.Users(_userIds); 86 | else 87 | target = _context.Clients.AllExcept(_excludedConnectionIds); 88 | 89 | // send the broadcast to the targeted connections 90 | target.sendLogEvent(new LogEvent(logEvent, logEvent.RenderMessage(_formatProvider))); 91 | } 92 | } 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/Serilog.Sinks.SignalR/app.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /src/Serilog.Sinks.SignalR/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | --------------------------------------------------------------------------------