diff --git a/.gitignore b/.gitignore index b6d0c7e..eb9a5e2 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,31 @@ -################################################################################ -# This .gitignore file was automatically created by Microsoft(R) Visual Studio. -################################################################################ +#Ignore thumbnails created by Windows +Thumbs.db -/CoreSrc/StackifyLib/bin/Debug/netcoreapp1.0/StackifyLib.pdb -Src/StackifyLib.log4net/project.lock.json +#Ignore files built by Visual Studio +*.obj +*.exe +*.pdb +*.user +*.aps +*.pch +*.vspscc +*_i.c +*_p.c +*.ncb +*.suo +*.tlb +*.tlh +*.bak +*.cache +*.ilk +*.log +*.dll +*.lib +*.sbr +.idea/ +_ReSharper.Caches/ +packages/ +*.lock.json + +**/bin/* +**/obj/* diff --git a/Src/NLog.Targets.Stackify/NLog.Targets.Stackify.csproj b/Src/NLog.Targets.Stackify/NLog.Targets.Stackify.csproj index b540512..0d9afb2 100644 --- a/Src/NLog.Targets.Stackify/NLog.Targets.Stackify.csproj +++ b/Src/NLog.Targets.Stackify/NLog.Targets.Stackify.csproj @@ -15,7 +15,7 @@ false false false - 2.0.0 + 2.0.1 https://github.com/stackify/stackify-api-dotnet/blob/master/LICENSE https://github.com/stackify/stackify-api-dotnet https://stackify.com/wp-content/uploads/2017/02/stk.png diff --git a/Src/NLog.Targets.Stackify/StackifyTarget.cs b/Src/NLog.Targets.Stackify/StackifyTarget.cs index b679d99..2374ad7 100644 --- a/Src/NLog.Targets.Stackify/StackifyTarget.cs +++ b/Src/NLog.Targets.Stackify/StackifyTarget.cs @@ -151,7 +151,8 @@ private Dictionary GetDiagnosticContextProperties() } } } - #if NET45 || NET40 + +#if NET45 || NET40 foreach (string key in _CallContextKeys) { @@ -163,8 +164,8 @@ private Dictionary GetDiagnosticContextProperties() } } #endif - return properties; + return properties; } internal LogMsg Translate(LogEventInfo loggingEvent) diff --git a/Src/StackifyLib.AspNetCore/StackifyLib.AspNetCore.csproj b/Src/StackifyLib.AspNetCore/StackifyLib.AspNetCore.csproj index 80a4add..7f0cf14 100644 --- a/Src/StackifyLib.AspNetCore/StackifyLib.AspNetCore.csproj +++ b/Src/StackifyLib.AspNetCore/StackifyLib.AspNetCore.csproj @@ -12,7 +12,7 @@ false false false - 2.0.0 + 2.0.1 StackifyLib.AspNetCore https://github.com/stackify/stackify-api-dotnet/blob/master/LICENSE https://github.com/stackify/stackify-api-dotnet diff --git a/Src/StackifyLib.CoreLogger/StackifyLib.CoreLogger.csproj b/Src/StackifyLib.CoreLogger/StackifyLib.CoreLogger.csproj index 4744589..5b999df 100644 --- a/Src/StackifyLib.CoreLogger/StackifyLib.CoreLogger.csproj +++ b/Src/StackifyLib.CoreLogger/StackifyLib.CoreLogger.csproj @@ -18,7 +18,7 @@ git https://stackify.com/wp-content/uploads/2017/02/stk.png StackifyLib.CoreLogger - 2.0.1 + 2.0.2 diff --git a/Src/StackifyLib.StackifyTraceListener/StackifyLib.StackifyTraceListener.csproj b/Src/StackifyLib.StackifyTraceListener/StackifyLib.StackifyTraceListener.csproj index b57bd07..4ed884d 100644 --- a/Src/StackifyLib.StackifyTraceListener/StackifyLib.StackifyTraceListener.csproj +++ b/Src/StackifyLib.StackifyTraceListener/StackifyLib.StackifyTraceListener.csproj @@ -9,7 +9,7 @@ false false false - 2.0.0 + 2.0.1 StackifyLib.StackifyTraceListener https://github.com/stackify/stackify-api-dotnet/blob/master/LICENSE https://github.com/stackify/stackify-api-dotnet diff --git a/Src/StackifyLib.log4net/StackifyLib.log4net.csproj b/Src/StackifyLib.log4net/StackifyLib.log4net.csproj index 7f1ecd5..67a3941 100644 --- a/Src/StackifyLib.log4net/StackifyLib.log4net.csproj +++ b/Src/StackifyLib.log4net/StackifyLib.log4net.csproj @@ -13,7 +13,7 @@ false false false - 2.0.0 + 2.0.1 https://github.com/stackify/stackify-api-dotnet/blob/master/LICENSE https://github.com/stackify/stackify-api-dotnet https://github.com/stackify/stackify-api-dotnet diff --git a/Src/StackifyLib/Config.cs b/Src/StackifyLib/Config.cs index e2c28ca..2c40080 100644 --- a/Src/StackifyLib/Config.cs +++ b/Src/StackifyLib/Config.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Text; using System.Diagnostics; +using StackifyLib.Utils; namespace StackifyLib { @@ -12,31 +13,28 @@ namespace StackifyLib /// public class Config { - #if NETSTANDARD1_3 || NET451 - private static Microsoft.Extensions.Configuration.IConfigurationRoot _Configuration = null; + private static Microsoft.Extensions.Configuration.IConfigurationRoot _configuration = null; public static void SetConfiguration(Microsoft.Extensions.Configuration.IConfigurationRoot configuration) { - _Configuration = configuration; + _configuration = configuration; } #endif + public static void LoadSettings() { try { - CaptureErrorPostdata = Get("Stackify.CaptureErrorPostdata", "") - .Equals("true", StringComparison.CurrentCultureIgnoreCase); + CaptureErrorPostdata = Get("Stackify.CaptureErrorPostdata", "").Equals(bool.TrueString, StringComparison.CurrentCultureIgnoreCase); + + CaptureServerVariables = Get("Stackify.CaptureServerVariables", "").Equals(bool.TrueString, StringComparison.CurrentCultureIgnoreCase); - CaptureServerVariables = Get("Stackify.CaptureServerVariables", "") - .Equals("true", StringComparison.CurrentCultureIgnoreCase); - CaptureSessionVariables = Get("Stackify.CaptureSessionVariables", "") - .Equals("true", StringComparison.CurrentCultureIgnoreCase); + CaptureSessionVariables = Get("Stackify.CaptureSessionVariables", "").Equals(bool.TrueString, StringComparison.CurrentCultureIgnoreCase); - CaptureErrorHeaders = Get("Stackify.CaptureErrorHeaders", "true").Equals("true", StringComparison.CurrentCultureIgnoreCase); + CaptureErrorHeaders = Get("Stackify.CaptureErrorHeaders", bool.TrueString).Equals(bool.TrueString, StringComparison.CurrentCultureIgnoreCase); - CaptureErrorCookies = Get("Stackify.CaptureErrorCookies", "") - .Equals("true", StringComparison.CurrentCultureIgnoreCase); + CaptureErrorCookies = Get("Stackify.CaptureErrorCookies", "").Equals(bool.TrueString, StringComparison.CurrentCultureIgnoreCase); ApiKey = Get("Stackify.ApiKey", ""); @@ -46,31 +44,31 @@ public static void LoadSettings() CaptureErrorHeadersWhitelist = Get("Stackify.CaptureErrorHeadersWhitelist", ""); - if (!string.IsNullOrEmpty(CaptureErrorHeadersWhitelist)) + if (string.IsNullOrEmpty(CaptureErrorHeadersWhitelist) == false) { ErrorHeaderGoodKeys = CaptureErrorHeadersWhitelist.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList(); } CaptureErrorHeadersBlacklist = Get("Stackify.CaptureErrorHeadersBlacklist", ""); - if (!string.IsNullOrEmpty(CaptureErrorHeadersBlacklist)) + if (string.IsNullOrEmpty(CaptureErrorHeadersBlacklist) == false) { ErrorHeaderBadKeys = CaptureErrorHeadersBlacklist.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList(); } CaptureErrorCookiesWhitelist = Get("Stackify.CaptureErrorCookiesWhitelist", ""); - if (!string.IsNullOrEmpty(CaptureErrorCookiesWhitelist)) + if (string.IsNullOrEmpty(CaptureErrorCookiesWhitelist) == false) { ErrorCookiesGoodKeys = CaptureErrorCookiesWhitelist.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList(); } CaptureErrorCookiesBlacklist = Get("Stackify.CaptureErrorCookiesBlacklist", ""); - if (!string.IsNullOrEmpty(CaptureErrorCookiesBlacklist)) + if (string.IsNullOrEmpty(CaptureErrorCookiesBlacklist) == false) { ErrorCookiesBadKeys = CaptureErrorCookiesBlacklist.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList(); } CaptureErrorSessionWhitelist = Get("Stackify.CaptureErrorSessionWhitelist", ""); - if (!string.IsNullOrEmpty(CaptureErrorSessionWhitelist)) + if (string.IsNullOrEmpty(CaptureErrorSessionWhitelist) == false) { ErrorSessionGoodKeys = CaptureErrorSessionWhitelist.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList(); } @@ -89,12 +87,19 @@ public static void LoadSettings() var isEc2 = Get("Stackify.IsEC2", ""); if (string.IsNullOrWhiteSpace(isEc2) == false) { - IsEc2 = isEc2.Equals("true", StringComparison.CurrentCultureIgnoreCase); + IsEc2 = isEc2.Equals(bool.TrueString, StringComparison.CurrentCultureIgnoreCase); } - } + + // RT-297 + var apiLog = Get("Stackify.ApiLog", ""); + if (string.IsNullOrWhiteSpace(apiLog) == false) + { + ApiLog = apiLog.Equals(bool.TrueString, StringComparison.CurrentCultureIgnoreCase); + } + } catch (Exception ex) { - Debug.WriteLine(ex.ToString()); + StackifyAPILogger.Log("#Config #LoadSettings failed", ex); } } @@ -129,6 +134,7 @@ public static void LoadSettings() public static bool? IsEc2 { get; set; } = null; + public static bool? ApiLog { get; set; } = null; /// /// Attempts to fetch a setting value given the key. @@ -140,35 +146,41 @@ public static void LoadSettings() internal static string Get(string key, string defaultValue = null) { string v = null; + try { if (key != null) { - - #if NETSTANDARD1_3 || NET451 - if (_Configuration != null) + if (_configuration != null) { - var appSettings = _Configuration.GetSection("Stackify"); + var appSettings = _configuration.GetSection("Stackify"); v = appSettings[key.Replace("Stackify.", "")]; } #endif -#if NET451 || NET45 || NET40 - if (string.IsNullOrEmpty(v)) - v = System.Configuration.ConfigurationManager.AppSettings[key]; +#if NET451 || NET45 + if (string.IsNullOrEmpty(v)) + { + v = System.Configuration.ConfigurationManager.AppSettings[key]; + } #endif - if (string.IsNullOrEmpty(v)) - v = System.Environment.GetEnvironmentVariable(key); + if (string.IsNullOrEmpty(v)) + { + v = System.Environment.GetEnvironmentVariable(key); + } } } finally { - if (v == null) - v = defaultValue; + if (v == null) + { + v = defaultValue; + } } + return v; } } -} +} \ No newline at end of file diff --git a/Src/StackifyLib/Extensions.cs b/Src/StackifyLib/Extensions.cs index 9c8b5f8..a068ce7 100644 --- a/Src/StackifyLib/Extensions.cs +++ b/Src/StackifyLib/Extensions.cs @@ -6,6 +6,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; +using StackifyLib.Utils; namespace StackifyLib { @@ -19,7 +20,7 @@ public static void SendToStackify(this Exception ex) } catch (Exception e) { - Debug.WriteLine("Error submitting error to Stackify " + e.ToString()); + StackifyAPILogger.Log("#Extensions #SendToStackify failed", e); throw; } } @@ -32,7 +33,7 @@ public static StackifyLib.StackifyError NewStackifyError(this Exception ex) } catch (Exception e) { - Debug.WriteLine("Error submitting error to Stackify " + e.ToString()); + StackifyAPILogger.Log("#Extensions #NewStackifyError failed", e); throw; } } diff --git a/Src/StackifyLib/Internal/Logs/LogQueue.cs b/Src/StackifyLib/Internal/Logs/LogQueue.cs index f8e1eda..b856f22 100644 --- a/Src/StackifyLib/Internal/Logs/LogQueue.cs +++ b/Src/StackifyLib/Internal/Logs/LogQueue.cs @@ -76,14 +76,15 @@ public void QueueLogMessage(Models.LogMsg msg) try { if (msg == null) + { return; + } if (!_TimerStarted) { EnsureTimer(); } - try { @@ -94,6 +95,7 @@ public void QueueLogMessage(Models.LogMsg msg) } catch { + // ignore } #if NET451 || NET45 || NET40 @@ -101,8 +103,7 @@ public void QueueLogMessage(Models.LogMsg msg) { if (string.IsNullOrEmpty(msg.TransID)) { - - Object stackifyRequestID = CallContext.LogicalGetData("Stackify-RequestID"); + var stackifyRequestID = CallContext.LogicalGetData("Stackify-RequestID"); if (stackifyRequestID != null) { @@ -114,7 +115,7 @@ public void QueueLogMessage(Models.LogMsg msg) { //gets from Trace.CorrelationManager.ActivityId but doesnt assume it is guid since it technically doesn't have to be //not calling the CorrelationManager method because it blows up if it isn't a guid - Object correltionManagerId = CallContext.LogicalGetData("E2ETrace.ActivityID"); + var correltionManagerId = CallContext.LogicalGetData("E2ETrace.ActivityID"); if (correltionManagerId != null && correltionManagerId is Guid && ((Guid)correltionManagerId) != Guid.Empty) { @@ -124,13 +125,13 @@ public void QueueLogMessage(Models.LogMsg msg) if (string.IsNullOrEmpty(msg.TransID)) { - if (_IsWebApp && System.Web.Hosting.HostingEnvironment.IsHosted - && System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Handler != null && - System.Web.HttpContext.Current.Request != null) + if (_IsWebApp + && System.Web.Hosting.HostingEnvironment.IsHosted + && System.Web.HttpContext.Current != null + && System.Web.HttpContext.Current.Handler != null) { msg.TransID = System.Web.HttpContext.Current.Request.GetHashCode().ToString(); } - } } catch (System.Web.HttpException ex) @@ -142,24 +143,22 @@ public void QueueLogMessage(Models.LogMsg msg) StackifyAPILogger.Log("Error figuring out TransID \r\n" + ex.ToString()); } - - - if (_IsWebApp && System.Web.Hosting.HostingEnvironment.IsHosted + if (_IsWebApp + && System.Web.Hosting.HostingEnvironment.IsHosted && System.Web.HttpContext.Current != null - && System.Web.HttpContext.Current.Handler != null - && System.Web.HttpContext.Current.Request != null) + && System.Web.HttpContext.Current.Handler != null) { var context = System.Web.HttpContext.Current; msg.UrlFull = context.Request.Url.ToString(); - if (context.Items != null && context.Items.Contains("Stackify.ReportingUrl")) + if (context.Items.Contains("Stackify.ReportingUrl")) { msg.UrlRoute = context.Items["Stackify.ReportingUrl"].ToString(); } else { - RouteResolver resolver = new RouteResolver(context); + var resolver = new RouteResolver(context); var route = resolver.GetRoute(); @@ -169,24 +168,21 @@ public void QueueLogMessage(Models.LogMsg msg) } } - if (string.IsNullOrEmpty(msg.UrlRoute)) { - HelperFunctions.CleanPartialUrl( - context.Request.AppRelativeCurrentExecutionFilePath.TrimStart('~')); + if (string.IsNullOrWhiteSpace(context.Request.AppRelativeCurrentExecutionFilePath) == false) + { + HelperFunctions.CleanPartialUrl(context.Request.AppRelativeCurrentExecutionFilePath.TrimStart('~')); + } } - - } - #endif _MessageBuffer.Enqueue(msg); - } - catch + catch (Exception ex) { - + StackifyAPILogger.Log("#LogQueue #QueueLogMessage failed", ex); } } @@ -194,11 +190,12 @@ public void QueueLogMessage(Models.LogMsg msg) private void OnTimer(Object stateInfo) { if (_PauseUpload) + { return; + } _timer.Change(-1, -1); //disable while it does this so it does fire multiple times - try { //remove messages in the queue that are old @@ -221,14 +218,16 @@ private void OnTimer(Object stateInfo) } if (_timer != null && !_StopRequested) + { _timer.Change(_FlushInterval, _FlushInterval); + } return; } } catch (Exception ex) { - StackifyLib.Utils.StackifyAPILogger.Log(ex.ToString()); + StackifyAPILogger.Log("#LogQueue #OnTimer failed", ex); } @@ -242,9 +241,7 @@ private void OnTimer(Object stateInfo) if (_FlushInterval.TotalSeconds > 1) { _FlushInterval = TimeSpan.FromSeconds(_FlushInterval.TotalSeconds / 2); - StackifyLib.Utils.StackifyAPILogger.Log( - string.Format("Adjust log flush interval down to {0:0.00} seconds", - _FlushInterval.TotalSeconds)); + StackifyAPILogger.Log(string.Format("#LogQueue Adjust log flush interval down to {0:0.00} seconds",_FlushInterval.TotalSeconds)); } } else if (processedCount < 10 && _FlushInterval != TimeSpan.FromSeconds(5)) @@ -264,19 +261,19 @@ private void OnTimer(Object stateInfo) { _FlushInterval = TimeSpan.FromSeconds(proposedSeconds); - StackifyLib.Utils.StackifyAPILogger.Log( - string.Format("Adjust log flush interval up to {0:0.00} seconds", - _FlushInterval.TotalSeconds)); + StackifyAPILogger.Log(string.Format("#LogQueue Adjust log flush interval up to {0:0.00} seconds",_FlushInterval.TotalSeconds)); } } } catch (Exception ex) { - StackifyLib.Utils.StackifyAPILogger.Log(ex.ToString()); + StackifyAPILogger.Log("#LogQueue #QueueLogMessage failed", ex); } if (_timer != null && !_StopRequested) + { _timer.Change(_FlushInterval, _FlushInterval); + } } @@ -320,7 +317,7 @@ private int FlushLoop() } catch (Exception ex) { - StackifyLib.Utils.StackifyAPILogger.Log(ex.ToString()); + StackifyAPILogger.Log("#LogQueue #FlushLoop failed", ex); } _UploadingNow = false; return processedCount; @@ -328,7 +325,6 @@ private int FlushLoop() private int FlushOnce() { - // StackifyLib.Utils.StackifyAPILogger.Log("Calling FlushOnceAsync"); int messageSize = 0; @@ -336,6 +332,7 @@ private int FlushOnce() //we only want to do this once at a time but the actual send is done async long startMs = (long)DateTime.UtcNow.Subtract(_Epoch).TotalMilliseconds; + try { while (true) @@ -344,7 +341,7 @@ private int FlushOnce() if (_MessageBuffer.TryDequeue(out msg)) { //do not log our own messages. This is to prevent any sort of recursion that could happen since calling to send this will cause even more logging to happen - if (msg.Msg != null & msg.Msg.IndexOf("StackifyLib:") > -1) + if (msg.Msg != null && msg.Msg != null && msg.Msg.Contains("StackifyLib:")) { //skip! continue; @@ -384,7 +381,7 @@ private int FlushOnce() if (response.IsClientError()) { - Utils.StackifyAPILogger.Log("Not requeueing log messages due to client error: " + response.StatusCode, true); + Utils.StackifyAPILogger.Log("#LogQueue Not requeueing log messages due to client error: " + response.StatusCode, true); } else { @@ -394,13 +391,12 @@ private int FlushOnce() if (messagesSentTooManyTimes) { - Utils.StackifyAPILogger.Log( - "Some messages not queued again due to too many failures uploading"); + Utils.StackifyAPILogger.Log("#LogQueue Some messages not queued again due to too many failures uploading"); } } catch (Exception ex2) { - Utils.StackifyAPILogger.Log("Error trying to requeue messages " + ex2.ToString()); + Utils.StackifyAPILogger.Log("#LogQueue Error trying to requeue messages " + ex2.ToString()); } } } @@ -408,7 +404,7 @@ private int FlushOnce() } catch (Exception ex) { - Utils.StackifyAPILogger.Log(ex.ToString()); + StackifyAPILogger.Log("#LogQueue #FlushOnce failed", ex); EnqueueForRetransmission(chunk); } @@ -419,7 +415,7 @@ private int FlushOnce() public void Stop() { - Utils.StackifyAPILogger.Log("LogQueue stop received"); + Utils.StackifyAPILogger.Log("#LogQueue stop received"); _StopRequested = true; if (!_UploadingNow) @@ -433,15 +429,11 @@ public void Stop() //wait for it to finish up to 5 seconds while (_UploadingNow && DateTime.UtcNow < stopWaiting) { -#if NET451 || NET45 || NET40 System.Threading.Thread.Sleep(10); -#else - Task.Delay(10).Wait(); -#endif } } - Utils.StackifyAPILogger.Log("LogQueue stop complete"); + Utils.StackifyAPILogger.Log("#LogQueue stop complete"); } public void Pause(bool isPaused) @@ -470,9 +462,9 @@ private bool EnqueueForRetransmission(List chunk) } } } - catch (Exception e) + catch (Exception ex) { - Utils.StackifyAPILogger.Log(e.ToString()); + StackifyAPILogger.Log("#LogQueue #EnqueueForRetransmission failed", ex); } return skippedMessage; diff --git a/Src/StackifyLib/Logger.cs b/Src/StackifyLib/Logger.cs index 38878f9..f22d0d8 100644 --- a/Src/StackifyLib/Logger.cs +++ b/Src/StackifyLib/Logger.cs @@ -254,57 +254,62 @@ public static void QueueLogObject(StackifyLib.Models.LogMsg msg, Exception excep /// Helper method for getting the current stack trace /// /// + /// + /// /// public static List GetCurrentStackTrace(string declaringClassName, int maxFrames = 99, bool simpleMethodNames = false) { - List frames = new List(); + var frames = new List(); #if NET451 || NET45 || NET40 try { //moves to the part of the trace where the declaring method starts then the other loop gets all the frames. This is to remove frames that happen within the logging library itself. - StackTrace stackTrace = new StackTrace(true); - int index1; + var stackTrace = new StackTrace(true); var stackTraceFrames = stackTrace.GetFrames(); - for (index1 = 0; index1 < stackTraceFrames.Length; ++index1) + if (stackTraceFrames != null) { - var frame = stackTraceFrames[index1]; + int index1; - if (frame != null) + for (index1 = 0; index1 < stackTraceFrames.Length; ++index1) { - var method = frame.GetMethod(); + var frame = stackTraceFrames[index1]; - if (method != null && method.DeclaringType != null && method.DeclaringType.FullName == declaringClassName) + if (frame != null) { - break; + var method = frame.GetMethod(); + + if (method != null && method.DeclaringType != null && + method.DeclaringType.FullName == declaringClassName) + { + break; + } } } - } - - if (index1 < stackTraceFrames.Length) - { - - for (int index2 = index1; index2 < stackTraceFrames.Length; ++index2) + if (index1 < stackTraceFrames.Length) { - var frame2 = stackTraceFrames[index2]; - var f2 = new TraceFrame(); - f2.CodeFileName = frame2.GetFileName(); - f2.LineNum = frame2.GetFileLineNumber(); - f2.Method = ErrorItem.GetMethodFullName(frame2.GetMethod(), simpleMethodNames); - frames.Add(f2); - - if (frames.Count > maxFrames) + + for (int index2 = index1; index2 < stackTraceFrames.Length; ++index2) { - return frames; + var frame2 = stackTraceFrames[index2]; + var f2 = new TraceFrame(); + f2.CodeFileName = frame2.GetFileName(); + f2.LineNum = frame2.GetFileLineNumber(); + f2.Method = ErrorItem.GetMethodFullName(frame2.GetMethod(), simpleMethodNames); + frames.Add(f2); + + if (frames.Count > maxFrames) + { + return frames; + } } } - } } - catch (Exception ex) + catch { - + // ignored } #endif return frames; diff --git a/Src/StackifyLib/Models/EnvironmentDetail.cs b/Src/StackifyLib/Models/EnvironmentDetail.cs index 87ea7f3..ef9dd45 100644 --- a/Src/StackifyLib/Models/EnvironmentDetail.cs +++ b/Src/StackifyLib/Models/EnvironmentDetail.cs @@ -17,7 +17,6 @@ namespace StackifyLib.Models { public class EnvironmentDetail { - private static EnvironmentDetail _CachedCopy = null; public static EnvironmentDetail Get(bool refresh) @@ -318,9 +317,6 @@ private void IsWindowService() #endif } - - - public EnvironmentDetail(bool loadDetails) { if (!loadDetails) diff --git a/Src/StackifyLib/Models/ErrorItem.cs b/Src/StackifyLib/Models/ErrorItem.cs index ca74b3c..3574446 100644 --- a/Src/StackifyLib/Models/ErrorItem.cs +++ b/Src/StackifyLib/Models/ErrorItem.cs @@ -17,7 +17,6 @@ public ErrorItem() public ErrorItem(Exception ex) { - try { var keys = ex.Data.Keys; @@ -32,6 +31,7 @@ public ErrorItem(Exception ex) } Message = ex.Message; + #if NET451 || NET45 || NET40 if (ex is System.Data.SqlClient.SqlException) { @@ -65,7 +65,6 @@ public ErrorItem(Exception ex) var t = ex.GetType(); - ErrorType = t.FullName; if (ex is StringException) @@ -76,7 +75,6 @@ public ErrorItem(Exception ex) { AddTraceFrames(ex); } - } catch (Exception e) { @@ -178,7 +176,6 @@ private void AddTraceFrames(Exception ex) } } - if (foundLast) { StackTrace.Add(new TraceFrame() @@ -189,13 +186,9 @@ private void AddTraceFrames(Exception ex) Method = GetMethodFullName(method) }); } - - } } #endif - - } public static string GetMethodFullName(MethodBase method, bool simpleMethodNames = false) diff --git a/Src/StackifyLib/Models/WebRequestDetail.cs b/Src/StackifyLib/Models/WebRequestDetail.cs index 12ff83d..57ea29d 100644 --- a/Src/StackifyLib/Models/WebRequestDetail.cs +++ b/Src/StackifyLib/Models/WebRequestDetail.cs @@ -145,12 +145,11 @@ private void Load(HttpContext context) ReportingUrl = route.ToString(); } } - catch (Exception) + catch { - + // ignored } - try { @@ -224,8 +223,9 @@ private void Load(HttpContext context) } } } - catch (Exception) + catch { + // ignored } } #endif @@ -264,9 +264,9 @@ internal static Dictionary ToKeyValues(HttpCookieCollection coll AddKey(key, cookie.Value, items, goodKeys, badKeys); } } - catch (Exception) + catch { - + // ignored } } @@ -285,9 +285,9 @@ internal static Dictionary ToKeyValues(NameValueCollection colle string val = collection[key]; AddKey(key, val, items, goodKeys, badKeys); } - catch (Exception) + catch { - + // ignored } } @@ -312,9 +312,9 @@ internal static Dictionary ToKeyValues(System.Web.SessionState.H } } - catch (Exception) + catch { - + // ignored } } diff --git a/Src/StackifyLib/ProfileTracer.cs b/Src/StackifyLib/ProfileTracer.cs index 7fd0a7d..8b67cbd 100644 --- a/Src/StackifyLib/ProfileTracer.cs +++ b/Src/StackifyLib/ProfileTracer.cs @@ -7,11 +7,11 @@ namespace StackifyLib { public class ProfileTracer { - private string _methodDisplayText = null; - private bool ignoreChildFrames = false; + private readonly string _methodDisplayText = null; + private bool _ignoreChildFrames = false; - private string _requestReportingCategory = null; - private string _appReportingCategory = null; + private readonly string _requestReportingCategory = null; + private readonly string _appReportingCategory = null; private bool _customMetricCount = false; private bool _customMetricTime = false; @@ -20,19 +20,21 @@ public class ProfileTracer private string _customMetricCategory = null; private string _customMetricName = null; - private string _transactionID = Guid.NewGuid().ToString(); - private string _RequestID = null; - internal bool IsOperation { get; set; } -#if NET45 || NETSTANDARD1_3 + private readonly string _transactionId = Guid.NewGuid().ToString(); + private string _requestId = null; + +#if NET45 || NET451 || NETSTANDARD1_3 private static EtwEventListener _etwEventListener = null; #endif + + internal bool IsOperation { get; set; } + internal ProfileTracer(string methodDisplayText, string requestLevelReportingCategory, string appLevelReportingCategory) { _methodDisplayText = methodDisplayText; _requestReportingCategory = requestLevelReportingCategory; _appReportingCategory = appLevelReportingCategory; - #if NET451 || NET45 || NET40 try { @@ -40,28 +42,27 @@ internal ProfileTracer(string methodDisplayText, string requestLevelReportingCat { var id = System.Web.HttpContext.Current.Items["Stackify-RequestID"]; - if (id != null && !string.IsNullOrEmpty(id.ToString())) + if (id != null && string.IsNullOrEmpty(id.ToString()) == false) { - _RequestID = id.ToString(); + _requestId = id.ToString(); } } - if (string.IsNullOrEmpty(_RequestID)) + if (string.IsNullOrEmpty(_requestId)) { - Object correltionManagerId = System.Runtime.Remoting.Messaging.CallContext.LogicalGetData("Stackify-RequestID"); + var correltionManagerId = System.Runtime.Remoting.Messaging.CallContext.LogicalGetData("Stackify-RequestID"); if (correltionManagerId != null) { - _RequestID = correltionManagerId.ToString(); + _requestId = correltionManagerId.ToString(); } } } - catch + catch (Exception ex) { - + StackifyAPILogger.Log("#ProfileTracer ctor", ex); } #endif - } [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] @@ -75,9 +76,9 @@ public static void SetReportingUrl(string reportingUrl) System.Web.HttpContext.Current.Items["Stackify.ReportingUrl"] = reportingUrl; } } - catch + catch (Exception ex) { - + StackifyAPILogger.Log("#ProfileTracer #SetReportingUrl", ex); } #endif } @@ -97,8 +98,6 @@ public static void NoOp() } - - [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] public static void TraceString(string logMsg) { @@ -118,19 +117,18 @@ public static void TraceMongoCommand(string logMsg) /// public static ProfileTracer CreateAsCodeBlock(string methodDisplayText) { - ProfileTracer tracer = new ProfileTracer(methodDisplayText, null, null); + var tracer = new ProfileTracer(methodDisplayText, null, null); return tracer; } /// /// Used by non web apps to define transactions in code that are turned in to operations to be tracked in Stackify APM or Prefix /// - /// - /// + /// /// public static ProfileTracer CreateAsTrackedFunction(string functionName) { - ProfileTracer tracer = new ProfileTracer(functionName, "Tracked Function", null); + var tracer = new ProfileTracer(functionName, "Tracked Function", null); return tracer; } @@ -142,16 +140,19 @@ public static ProfileTracer CreateAsTrackedFunction(string functionName) /// public static ProfileTracer CreateAsOperation(string operationName, string uniqueOperationID = null) { -#if NET45 || NETSTANDARD1_3 +#if NET45 || NET451 || NETSTANDARD1_3 if (_etwEventListener == null) + { _etwEventListener = new EtwEventListener(); + } #endif - ProfileTracer tracer = new ProfileTracer(operationName, null, null); + + var tracer = new ProfileTracer(operationName, null, null); tracer.IsOperation = true; - if (!string.IsNullOrEmpty(uniqueOperationID)) + if (string.IsNullOrEmpty(uniqueOperationID) == false) { - tracer._RequestID = uniqueOperationID; + tracer._requestId = uniqueOperationID; } return tracer; @@ -161,20 +162,21 @@ public static ProfileTracer CreateAsOperation(string operationName, string uniqu /// Used to logically group a section of code /// /// + /// + /// /// - public static ProfileTracer CreateAsDependency(string methodDisplayText, string requestLevelReportingCategory, string appLevelReportingCategory = null) { - ProfileTracer tracer = new ProfileTracer(methodDisplayText, requestLevelReportingCategory, appLevelReportingCategory); + var tracer = new ProfileTracer(methodDisplayText, requestLevelReportingCategory, appLevelReportingCategory); return tracer; } public ProfileTracer SetUniqueOperationID(string uniqueOperationID) { - if (!string.IsNullOrEmpty(uniqueOperationID)) + if (string.IsNullOrEmpty(uniqueOperationID) == false) { - this._RequestID = uniqueOperationID; + this._requestId = uniqueOperationID; } return this; @@ -193,7 +195,7 @@ public ProfileTracer CreateMetric(string categoryName, string metricName, bool t public ProfileTracer IgnoreChildFrames(bool value = true) { - ignoreChildFrames = value; + _ignoreChildFrames = value; return this; } @@ -207,8 +209,7 @@ private void ExecInternal2(string values, Action action) } finally { - ExecInternalComplete2(_transactionID + "|" + _RequestID + "|0|" + IsOperation); - + ExecInternalComplete2(_transactionId + "|" + _requestId + "|0|" + IsOperation); } } @@ -223,24 +224,23 @@ private void ExecInternalOperation(string values, Action action) } finally { - ExecInternalComplete2(_transactionID + "|" + _RequestID + "|0|" + IsOperation); - + ExecInternalComplete2(_transactionId + "|" + _requestId + "|0|" + IsOperation); } } [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] private Task ExecInternal2(string values, Func action) { - Task t = action(); - ExecInternalTaskStarted2(_transactionID + "|" + t.Id + "|" + IsOperation); + var t = action(); + ExecInternalTaskStarted2(_transactionId + "|" + t.Id + "|" + IsOperation); return t; } [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] private Task ExecInternal2(string values, Func> action) { - Task t = action(); - ExecInternalTaskStarted2(_transactionID + "|" + t.Id + "|" + IsOperation); + var t = action(); + ExecInternalTaskStarted2(_transactionId + "|" + t.Id + "|" + IsOperation); return t; } @@ -248,71 +248,69 @@ private Task ExecInternal2(string values, Func> action) [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] private Task ExecInternalOperation(string values, Func action) { - Task t = action(); - ExecInternalTaskStarted2(_transactionID + "|" + t.Id + "|" + IsOperation); + var t = action(); + ExecInternalTaskStarted2(_transactionId + "|" + t.Id + "|" + IsOperation); return t; } [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] private Task ExecInternalOperation(string values, Func> action) { - Task t = action(); - ExecInternalTaskStarted2(_transactionID + "|" + t.Id + "|" + IsOperation); + var t = action(); + ExecInternalTaskStarted2(_transactionId + "|" + t.Id + "|" + IsOperation); return t; } - [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] private void ExecInternalTaskStarted2(string values) { } - public void Exec(Action action) { if (action == null) + { return; - DateTimeOffset now = DateTimeOffset.UtcNow; + } + + var now = DateTimeOffset.UtcNow; if (this.IsOperation) { - ExecInternalOperation(_methodDisplayText + "|" + (ignoreChildFrames ? 1 : 0).ToString() + "|" + _requestReportingCategory + "|" + _appReportingCategory + "|" + _transactionID + "|" + _RequestID + "|" + IsOperation, action); + ExecInternalOperation(_methodDisplayText + "|" + (_ignoreChildFrames ? 1 : 0) + "|" + _requestReportingCategory + "|" + _appReportingCategory + "|" + _transactionId + "|" + _requestId + "|" + IsOperation, action); } else { - ExecInternal2(_methodDisplayText + "|" + (ignoreChildFrames ? 1 : 0).ToString() + "|" + _requestReportingCategory + "|" + _appReportingCategory + "|" + _transactionID + "|" + _RequestID + "|" + IsOperation, action); + ExecInternal2(_methodDisplayText + "|" + (_ignoreChildFrames ? 1 : 0) + "|" + _requestReportingCategory + "|" + _appReportingCategory + "|" + _transactionId + "|" + _requestId + "|" + IsOperation, action); } - if (_customMetricTime) { Metrics.Time(_customMetricCategory, _customMetricName + " Time", now); } - if (_customMetricCount) { Metrics.Count(_customMetricCategory, _customMetricName, 1, _autoReportZeroIfNothingReported); } - } public Task ExecAsync(Func> task) { - DateTimeOffset now = DateTimeOffset.UtcNow; + var now = DateTimeOffset.UtcNow; Task t; if (this.IsOperation) { - t = ExecInternalOperation(_methodDisplayText + "|" + (ignoreChildFrames ? 1 : 0).ToString() + "|" + _requestReportingCategory + "|" + _appReportingCategory + "|" + _transactionID + "|" + _RequestID + "|" + IsOperation, task); + t = ExecInternalOperation(_methodDisplayText + "|" + (_ignoreChildFrames ? 1 : 0) + "|" + _requestReportingCategory + "|" + _appReportingCategory + "|" + _transactionId + "|" + _requestId + "|" + IsOperation, task); } else { - t = ExecInternal2(_methodDisplayText + "|" + (ignoreChildFrames ? 1 : 0).ToString() + "|" + _requestReportingCategory + "|" + _appReportingCategory + "|" + _transactionID + "|" + _RequestID + "|" + IsOperation, task); + t = ExecInternal2(_methodDisplayText + "|" + (_ignoreChildFrames ? 1 : 0) + "|" + _requestReportingCategory + "|" + _appReportingCategory + "|" + _transactionId + "|" + _requestId + "|" + IsOperation, task); } t.ContinueWith((tend) => @@ -321,7 +319,7 @@ public Task ExecAsync(Func> task) { Metrics.Time(_customMetricCategory, _customMetricName + " Time", now); } - ExecInternalComplete2(_transactionID + "|" + _RequestID + "|" + tend.Id + "|" + IsOperation); + ExecInternalComplete2(_transactionId + "|" + _requestId + "|" + tend.Id + "|" + IsOperation); }); if (_customMetricCount) @@ -334,18 +332,18 @@ public Task ExecAsync(Func> task) public Task ExecAsync(Func task) { - DateTimeOffset now = DateTimeOffset.UtcNow; + var now = DateTimeOffset.UtcNow; Task t; if (this.IsOperation) { - t = ExecInternalOperation(_methodDisplayText + "|" + (ignoreChildFrames ? 1 : 0).ToString() + "|" + _requestReportingCategory + "|" + _appReportingCategory + "|" + _transactionID + "|" + _RequestID + "|" + IsOperation, task); + t = ExecInternalOperation(_methodDisplayText + "|" + (_ignoreChildFrames ? 1 : 0) + "|" + _requestReportingCategory + "|" + _appReportingCategory + "|" + _transactionId + "|" + _requestId + "|" + IsOperation, task); } else { - t = ExecInternal2(_methodDisplayText + "|" + (ignoreChildFrames ? 1 : 0).ToString() + "|" + _requestReportingCategory + "|" + _appReportingCategory + "|" + _transactionID + "|" + _RequestID + "|" + IsOperation, task); + t = ExecInternal2(_methodDisplayText + "|" + (_ignoreChildFrames ? 1 : 0) + "|" + _requestReportingCategory + "|" + _appReportingCategory + "|" + _transactionId + "|" + _requestId + "|" + IsOperation, task); } t.ContinueWith((tend) => @@ -354,7 +352,7 @@ public Task ExecAsync(Func task) { Metrics.Time(_customMetricCategory, _customMetricName + " Time", now); } - ExecInternalComplete2(_transactionID + "|" + _RequestID + "|" + tend.Id + "|" + IsOperation); + ExecInternalComplete2(_transactionId + "|" + _requestId + "|" + tend.Id + "|" + IsOperation); }); if (_customMetricCount) @@ -371,6 +369,5 @@ private void ExecInternalComplete2(string values) { } - } } diff --git a/Src/StackifyLib/StackifyError.cs b/Src/StackifyLib/StackifyError.cs index 23dc761..2a5ab2c 100644 --- a/Src/StackifyLib/StackifyError.cs +++ b/Src/StackifyLib/StackifyError.cs @@ -159,12 +159,11 @@ private void Init() } } } + #elif NETSTANDARD1_3 WebRequestDetail = new WebRequestDetail(this); #endif - - //Fire event OnCaptureDetail?.Invoke(this); @@ -196,8 +195,6 @@ public StackifyError SetAdditionalMessage(string message) } - - public static StackifyError New(Exception ex) { return new StackifyError(ex); @@ -219,10 +216,9 @@ public static bool IgnoreError(StackifyError ex) // ignore = true; //} } - catch (Exception) + catch { - - + // ignored } return ignore; @@ -244,10 +240,9 @@ public static bool IgnoreError(Exception ex) // ignore = true; //} } - catch (Exception) + catch { - - + // ignored } return ignore; diff --git a/Src/StackifyLib/StackifyLib.csproj b/Src/StackifyLib/StackifyLib.csproj index e39394a..aa0173a 100644 --- a/Src/StackifyLib/StackifyLib.csproj +++ b/Src/StackifyLib/StackifyLib.csproj @@ -14,15 +14,15 @@ false false false - 2.0.1 + 2.0.2 StackifyLib https://github.com/stackify/stackify-api-dotnet https://github.com/stackify/stackify-api-dotnet/blob/master/LICENSE https://github.com/stackify/stackify-api-dotnet git https://stackify.com/wp-content/uploads/2017/02/stk.png - 2.0.1.0 - 2.0.1.0 + 2.0.2.0 + 2.0.2.0 diff --git a/Src/StackifyLib/Utils/EtwEventListener.cs b/Src/StackifyLib/Utils/EtwEventListener.cs index 6d85521..a30c04c 100644 --- a/Src/StackifyLib/Utils/EtwEventListener.cs +++ b/Src/StackifyLib/Utils/EtwEventListener.cs @@ -1,4 +1,4 @@ -#if NET45 || NETSTANDARD1_3 +#if NET45 || NET451 || NETSTANDARD1_3 using System; using System.Collections.Generic; using System.Diagnostics; @@ -9,7 +9,7 @@ namespace StackifyLib.Utils { - public class EtwEventListener : System.Diagnostics.Tracing.EventListener + public class EtwEventListener : EventListener { private static readonly Guid tplGuid = new Guid("2e5dba47-a3d2-4d16-8ee0-6671ffdcd7b5"); // private static readonly Guid aspnetGuid = new Guid("aff081fe-0247-4275-9c4e-021f3dc1da35"); diff --git a/Src/StackifyLib/Utils/StackifyAPILogger.cs b/Src/StackifyLib/Utils/StackifyAPILogger.cs index 83796ea..bffa4a8 100644 --- a/Src/StackifyLib/Utils/StackifyAPILogger.cs +++ b/Src/StackifyLib/Utils/StackifyAPILogger.cs @@ -3,6 +3,7 @@ using System.Diagnostics; using System.IO; using System.Linq; +using System.Reflection; using System.Text; using System.Threading.Tasks; @@ -10,10 +11,16 @@ namespace StackifyLib.Utils { public class StackifyAPILogger { - private static StringWriter _Logger = null; +#if NETSTANDARD1_3 + private static readonly string DefaultLoggerPathAndFile = Path.Combine(System.AppContext.BaseDirectory, "stackify.debug.log"); +#elif NET451 || NET45 || NET40 + private static readonly string DefaultLoggerPathAndFile = Path.Combine(Environment.CurrentDirectory, "stackify.debug.log"); +#endif + private static readonly object LoggerDefaultLock = new object(); + private static StreamWriter _loggerDefault; - //must start with null so EvaluateLogEnabled() works below - private static bool? _LogEnabled = null; + private static StringWriter _logger; + private static bool? _logEnabled; public delegate void LogMessageHandler(string data); public static event LogMessageHandler OnLogMessage; @@ -27,66 +34,95 @@ public static bool LogEnabled { get { - EvaluateLogEnabled(); - return _LogEnabled ?? false; + var enabled = _logEnabled ?? false; + + return enabled; } set { - _LogEnabled = value; - Log("Logging enabled via code to value " + value.ToString()); + _logEnabled = value; } } - public static StringWriter Logger { set { - _Logger = value; + _logger = value; } } + + public static void Log(string message, bool logAnyways = false) { try { - if (logAnyways || (_LogEnabled ?? false)) + if (logAnyways || (_logEnabled ?? false)) { - OnLogMessage?.Invoke("StackifyLib: " + message); + var msg = $"{DateTime.UtcNow:yyyy/MM/dd HH:mm:ss,fff}/GMT StackifyLib: {message}"; + + OnLogMessage?.Invoke(msg); - if (_Logger != null) + if (_logger != null) { - _Logger.Write("StackifyLib: " + message); + _logger.Write(msg); } else { - Debug.WriteLine("StackifyLib: " + message); + Debug.WriteLine(msg); + + lock (LoggerDefaultLock) + { + if (_loggerDefault == null) + { + _loggerDefault = new StreamWriter(new FileStream(DefaultLoggerPathAndFile, FileMode.Append, FileAccess.Write, FileShare.Read)); + } + } + + _loggerDefault.WriteLine(msg); } } } - catch + catch (Exception ex) + { + Debug.WriteLine($"#StackifyAPILogger #Log failed\r\n{ex}"); + } + } + + public static void Log(string message, Exception ex, bool logAnyways = false) + { + try { + if (logAnyways || (_logEnabled ?? false)) + { + var msg = $"{message}\r\n{ex}"; + Log(msg); + } + } + catch + { + Debug.WriteLine($"#StackifyAPILogger #Log failed\r\n{ex}"); } - } private static void EvaluateLogEnabled() { - if (_LogEnabled == null) + if (_logEnabled == null) { - var setting = Config.Get("Stackify.ApiLog"); + var setting = Config.Get("Stackify.ApiLog"); - if (setting != null && setting.Equals("true", StringComparison.CurrentCultureIgnoreCase)) + if (setting != null && setting.Equals(bool.TrueString, StringComparison.CurrentCultureIgnoreCase)) { - _LogEnabled = true; + _logEnabled = true; - Log("StackifyLib: API Logger is enabled"); + Log("API Logger is enabled"); } else { - _LogEnabled = false; - Log("StackifyLib: API Logger is disabled"); + _logEnabled = false; + Log("API Logger is disabled"); } } }