Example #1
0
        private static IEnumerable <KeyValuePair <string, string> > GetClaims(Microsoft.AspNetCore.Http.HttpRequest httpRequest)
        {
            if (httpRequest == null)
            {
                throw new ArgumentNullException(nameof(httpRequest));
            }

            IIdentity identity = httpRequest.HttpContext?.User?.Identity;

            if (identity == null)
            {
                return(new List <KeyValuePair <string, string> >());
            }

            if (identity is ClaimsIdentity == false)
            {
                return(new List <KeyValuePair <string, string> >());
            }

            ClaimsIdentity claimsIdentity = identity as ClaimsIdentity;

            List <KeyValuePair <string, string> > claims = InternalHelpers.ToKeyValuePair(claimsIdentity);

            return(claims);
        }
Example #2
0
        public static KissLog.Http.HttpRequest Create(Microsoft.AspNetCore.Http.HttpRequest httpRequest)
        {
            if (httpRequest == null)
            {
                throw new ArgumentNullException(nameof(httpRequest));
            }

            Session session = KissLog.InternalHelpers.WrapInTryCatch(() => GetSession(httpRequest));

            session = session ?? new Session();

            bool isAuthenticated = httpRequest.HttpContext?.User?.Identity?.IsAuthenticated ?? false;

            KissLog.Http.HttpRequest result = new KissLog.Http.HttpRequest(new KissLog.Http.HttpRequest.CreateOptions
            {
                Url             = new Uri(httpRequest.GetDisplayUrl()),
                HttpMethod      = httpRequest.Method,
                UserAgent       = GetUserAgent(httpRequest.Headers),
                HttpReferer     = GetHttpReferrer(httpRequest.Headers),
                RemoteAddress   = httpRequest.HttpContext?.Connection?.RemoteIpAddress?.ToString(),
                MachineName     = InternalHelpers.GetMachineName(),
                IsNewSession    = session.IsNewSession,
                SessionId       = session.SessionId,
                IsAuthenticated = isAuthenticated
            });

            RequestProperties.CreateOptions propertiesOptions = new RequestProperties.CreateOptions();
            propertiesOptions.Cookies     = InternalHelpers.ToKeyValuePair(httpRequest.Cookies);
            propertiesOptions.Headers     = InternalHelpers.ToKeyValuePair(httpRequest.Headers);
            propertiesOptions.QueryString = InternalHelpers.ToKeyValuePair(httpRequest.Query);
            propertiesOptions.Claims      = GetClaims(httpRequest);

            if (httpRequest.HasFormContentType)
            {
                if (KissLogConfiguration.Options.Handlers.ShouldLogFormData.Invoke(result) == true)
                {
                    propertiesOptions.FormData = InternalHelpers.ToKeyValuePair(httpRequest.Form);
                }
            }

            if (KissLog.InternalHelpers.CanReadRequestInputStream(propertiesOptions.Headers))
            {
                if (KissLogConfiguration.Options.Handlers.ShouldLogInputStream.Invoke(result) == true)
                {
                    propertiesOptions.InputStream = KissLog.InternalHelpers.WrapInTryCatch(() =>
                    {
                        return(ModuleInitializer.ReadInputStreamProvider.ReadInputStream(httpRequest));
                    });
                }
            }

            result.SetProperties(new RequestProperties(propertiesOptions));

            return(result);
        }
Example #3
0
        public static void SetStatusCode(this ILogger logger, int statusCode)
        {
            if (logger == null)
            {
                return;
            }

            Logger kisslogger = KissLog.InternalHelpers.WrapInTryCatch(() => InternalHelpers.TryGetKissLogLogger(logger));

            if (kisslogger != null)
            {
                kisslogger.SetStatusCode(statusCode);
            }
        }
Example #4
0
        public static void LogResponseBody(this ILogger logger, bool value)
        {
            if (logger == null)
            {
                return;
            }

            Logger kisslogger = KissLog.InternalHelpers.WrapInTryCatch(() => InternalHelpers.TryGetKissLogLogger(logger));

            if (kisslogger != null)
            {
                kisslogger.LogResponseBody(value);
            }
        }
        public static void LogAsFile(this ILogger logger, string contents, string fileName = null)
        {
            if (logger == null)
            {
                return;
            }

            Logger kisslogger = KissLog.InternalHelpers.WrapInTryCatch(() => InternalHelpers.TryGetKissLogLogger(logger));

            if (kisslogger != null)
            {
                kisslogger.LogAsFile(contents, fileName);
            }
        }
        public static void AddCustomProperty(this ILogger logger, string name, DateTime value)
        {
            if (logger == null)
            {
                return;
            }

            Logger kisslogger = KissLog.InternalHelpers.WrapInTryCatch(() => InternalHelpers.TryGetKissLogLogger(logger));

            if (kisslogger != null)
            {
                kisslogger.AddCustomProperty(name, value);
            }
        }
Example #7
0
        public static bool AutoFlush(this ILogger logger)
        {
            if (logger == null)
            {
                return(false);
            }

            Logger kisslogger = KissLog.InternalHelpers.WrapInTryCatch(() => InternalHelpers.TryGetKissLogLogger(logger));

            if (kisslogger != null)
            {
                return(kisslogger.AutoFlush());
            }

            return(false);
        }
        public static HttpResponse Create(Microsoft.AspNetCore.Http.HttpResponse httpResponse, long contentLength)
        {
            if (httpResponse == null)
            {
                throw new ArgumentNullException(nameof(httpResponse));
            }

            if (contentLength < 0)
            {
                throw new ArgumentException(nameof(contentLength));
            }

            var options = new HttpResponse.CreateOptions();

            options.StatusCode = httpResponse.StatusCode;
            options.Properties = new ResponseProperties(new ResponseProperties.CreateOptions
            {
                Headers       = InternalHelpers.ToKeyValuePair(httpResponse.Headers),
                ContentLength = contentLength
            });

            return(new HttpResponse(options));
        }
        public async Task Invoke(HttpContext context)
        {
            Logger logger = Logger.Factory.Get() as Logger;

            if (logger == null)
            {
                return;
            }

            logger.DataContainer.AddProperty(InternalHelpers.IsCreatedByHttpRequest, true);

            WebRequestProperties properties = WebRequestPropertiesFactory.Create(context.Request);

            Exception     ex = null;
            Stream        originalBodyStream = context.Response.Body;
            TemporaryFile responseBodyFile   = null;
            long          contentLength      = 0;

            try
            {
                using (var responseStream = new MemoryStream())
                {
                    context.Response.Body = responseStream;

                    await _next(context);

                    responseBodyFile = new TemporaryFile();
                    await ReadResponse(context.Response, responseBodyFile.FileName);

                    contentLength = responseStream.Length;

                    if (CanWriteToResponseBody(context.Response))
                    {
                        await responseStream.CopyToAsync(originalBodyStream);
                    }
                }
            }
            catch (Exception e)
            {
                ex = e;
                throw;
            }
            finally
            {
                context.Response.Body = originalBodyStream;

                properties.EndDateTime = DateTime.UtcNow;

                HttpStatusCode statusCode = (HttpStatusCode)context.Response.StatusCode;

                if (ex != null)
                {
                    statusCode = HttpStatusCode.InternalServerError;
                    logger.Log(LogLevel.Error, ex);
                }

                if (logger.DataContainer.ExplicitHttpStatusCode.HasValue)
                {
                    statusCode = logger.DataContainer.ExplicitHttpStatusCode.Value;
                }

                ResponseProperties response = ResponsePropertiesFactory.Create(context.Response);
                response.HttpStatusCode = statusCode;
                response.ContentLength  = contentLength;
                properties.Response     = response;

                if (responseBodyFile != null && InternalHelpers.PreFilterShouldLogResponseBody(logger, responseBodyFile, response))
                {
                    string responseFileName = InternalHelpers.ResponseFileName(response.Headers);
                    logger.LogFile(responseBodyFile.FileName, responseFileName);
                }

                logger.DataContainer.WebRequestProperties = properties;

                responseBodyFile?.Dispose();

                IEnumerable <ILogger> loggers = Logger.Factory.GetAll();

                Logger.NotifyListeners(loggers.ToArray());
            }
        }
        public static WebRequestProperties Create(HttpRequest request)
        {
            WebRequestProperties result = new WebRequestProperties();

            if (request == null)
            {
                return(result);
            }

            try
            {
                if (request.HttpContext.Session != null && request.HttpContext.Session.IsAvailable)
                {
                    bool isNewSession = false;

                    string lastSessionId = request.HttpContext.Session.GetString("X-KissLogSessionId");
                    if (string.IsNullOrEmpty(lastSessionId) || string.Compare(lastSessionId, request.HttpContext.Session.Id, StringComparison.OrdinalIgnoreCase) != 0)
                    {
                        isNewSession = true;
                        request.HttpContext.Session.SetString("X-KissLogSessionId", request.HttpContext.Session.Id);
                    }

                    result.IsNewSession = isNewSession;
                    result.SessionId    = request.HttpContext.Session.Id;
                }
            }
            catch
            {
                // ignored
            }

            result.StartDateTime = DateTime.UtcNow;
            result.UserAgent     = request.Headers[HeaderNames.UserAgent].ToString();

            string url = request.GetDisplayUrl();

            result.Url = new Uri(url);

            result.MachineName = GetMachineName();

            RequestProperties requestProperties = new RequestProperties();

            result.Request = requestProperties;

            AddUserClaims(request, result);

            result.RemoteAddress = request.HttpContext.Connection?.RemoteIpAddress?.ToString();
            result.HttpMethod    = request.Method;

            string httpReferer        = null;
            string requestContentType = null;
            string inputStream        = null;

            foreach (string key in request.Headers.Keys)
            {
                if (string.Compare(key, "Cookie", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    continue;
                }

                StringValues values;
                request.Headers.TryGetValue(key, out values);

                string value = values.ToString();

                requestProperties.Headers.Add(new KeyValuePair <string, string>(key, value));

                if (string.Compare(key, "Referer", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    httpReferer = value;
                }

                if (string.Compare(key, "Content-Type", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    requestContentType = value;
                }
            }

            foreach (string key in request.Cookies.Keys)
            {
                string value = request.Cookies[key];

                requestProperties.Cookies.Add(new KeyValuePair <string, string>(key, value));
            }

            foreach (string key in request.Query.Keys)
            {
                string value = string.Join("; ", request.Query[key]);

                requestProperties.QueryString.Add(
                    new KeyValuePair <string, string>(key, value)
                    );
            }

            if (request.HasFormContentType)
            {
                foreach (string key in request.Form.Keys)
                {
                    string value = string.Join("; ", request.Form[key]);
                    requestProperties.FormData.Add(new KeyValuePair <string, string>(key, value));
                }
            }

            if (InternalHelpers.ShouldLogInputStream(requestProperties.Headers))
            {
                inputStream = ReadInputStream(request);
            }

            result.HttpReferer         = httpReferer;
            result.Request.InputStream = inputStream;

            return(result);
        }