Пример #1
0
 public void Log(string text, Severities severity = Severities.Info, [CallerMemberName] string caller = null)
 {
     if (Enabled)
     {
         _adapter.Log($"{DateTime.Now.TimeOfDay.ToString()} {severity} {caller} {text}", severity);
     }
 }
Пример #2
0
        /// <summary>
        /// Waiting for 'if' triggers
        /// or scheduler
        /// </summary>
        private void BecomePending()
        {
            BecomeState(ActionStateEnum.Pending, () =>
            {
                _logger.Debug($"Action {_sceneAction.Name} become Pending");
                Become(() =>
                {
                    Receive <MqttMessageEvent>(e =>
                    {
                        _stateObj.Update(e);
                        ProcessStateObj();
                        ScheduleTimeoutIfNotExists();
                    });
                    Receive <ScheduleEvent>(e =>
                    {
                        _stateObj.Update(e);
                        ProcessStateObj();
                        ScheduleTimeoutIfNotExists();
                    });
                    Receive <TimedOut>(e =>
                    {
                        _logger.Log(LogLevel.InfoLevel, "Receive timed out message. Become idle");
                        //notify fail
                        PubSubPub(new ActionResultEvent
                        {
                            ActionName = _sceneAction.Name,
                            Result     = ActionResultEnum.Fail
                        });
                        BecomeIdle();
                    });
                });

                ProcessStateObj();
            });
        }
Пример #3
0
        public string EntityId(object message)
        {
            if (message is SubscriptionMessage)
            {
                _adapter.Log(LogLevel.InfoLevel, $"SubscriptionMesage id was {((SubscriptionMessage)message).SubscriptionId.Id}");
            }

            _adapter.Log(LogLevel.InfoLevel, $"Getting entity id for type {message.GetType()} from {_messageExtractor.GetType()}");
            var result = _messageExtractor.EntityId(message);

            _adapter.Log(LogLevel.InfoLevel, $"Entity id was {result}");
            return(result);
        }
Пример #4
0
        /// <summary>
        /// Processes the incoming request. This method is not depended on the environment and so can be unit tested.
        /// Note that the incoming request may not be the POST request with log data.
        ///
        /// Effect of this method:
        /// * setting StatusCode on the response parameter
        /// * adding headers to the response parameter
        /// * logging contents of log request
        /// </summary>
        /// <param name="json">
        /// JSON payload in the incoming request
        /// </param>
        /// <param name="logRequestBase">
        /// * Type of browser that sent the request
        /// * IP address that sent the address
        /// * Url that the request was sent to
        /// * Request Id sent as part of the request
        /// * Request data to be given to onLogging event handler
        /// </param>
        /// <param name="serverSideTimeUtc">Current time in UTC</param>
        /// <param name="httpMethod">HTTP method of the request</param>
        /// <param name="origin">Value of the Origin request header</param>
        /// <param name="response">
        /// Empty response object. This method can add headers, etc.
        /// </param>
        internal static void ProcessLogRequest(string json, LogRequestBase logRequestBase,
                                               DateTime serverSideTimeUtc,
                                               string httpMethod, string origin, LogResponse response)
        {
            JsnlogConfiguration jsnlogConfiguration = JavascriptLogging.GetJsnlogConfiguration();

            ILoggingAdapter logger = JavascriptLogging.GetLogger();

            if ((httpMethod != "POST") && (httpMethod != "OPTIONS"))
            {
                response.StatusCode = (int)HttpStatusCode.MethodNotAllowed;
                return;
            }

            string corsAllowedOriginsRegex = jsnlogConfiguration.corsAllowedOriginsRegex;
            bool   originIsAllowed         = ((!string.IsNullOrEmpty(corsAllowedOriginsRegex)) && (!string.IsNullOrEmpty(origin)) && Regex.IsMatch(origin, corsAllowedOriginsRegex));

            if (originIsAllowed)
            {
                response.AppendHeader("Access-Control-Allow-Origin", origin);
            }

            response.StatusCode = (int)HttpStatusCode.OK;

            if (httpMethod == "OPTIONS")
            {
                // Standard HTTP response (not related to CORS)
                response.AppendHeader("Allow", "POST");

                // Only if the origin is allowed send CORS headers
                if (originIsAllowed)
                {
                    response.AppendHeader("Access-Control-Max-Age", Constants.CorsAccessControlMaxAgeInSeconds.ToString());
                    response.AppendHeader("Access-Control-Allow-Methods", "POST");
                    response.AppendHeader("Access-Control-Allow-Headers", "jsnlog-requestid, content-type");
                }

                return;
            }

            // httpMethod must be POST

            List <FinalLogData> logDatas =
                ProcessLogRequestExec(json, logRequestBase, serverSideTimeUtc, jsnlogConfiguration);

            // ---------------------------------
            // Pass log data to Common Logging

            foreach (FinalLogData logData in logDatas)
            {
                logger.Log(logData);
            }
        }
        public void ShouldHandleSerilogFormats(LogLevel level, string formatStr, object[] args)
        {
            Sys.EventStream.Subscribe(TestActor, typeof(LogEvent));

            Action logWrite = () =>
            {
                _loggingAdapter.Log(level, formatStr, args);

                var logEvent = ExpectMsg <LogEvent>();
                logEvent.LogLevel().Should().Be(level);
                logEvent.ToString().Should().NotBeEmpty();
            };

            logWrite.Should().NotThrow <FormatException>();
        }
Пример #6
0
        public void LoggingTest(LogLevel level, string formatStr, object[] formatArgs, string resultStr)
        {
            _loggingTarget.Logs.Clear();
            _loggingAdapter.Log(level, formatStr, formatArgs);

            for (int i = 0; i < 100; ++i)
            {
                if (_loggingTarget.Logs.Count != 0)
                {
                    break;
                }

                System.Threading.Thread.Sleep(10);
            }

            Assert.NotEmpty(_loggingTarget.Logs);
            Assert.Equal(resultStr, _loggingTarget.Logs.Last());
        }
Пример #7
0
 private void BuildResponseAndCache()
 {
     this.cache = null;
     if (this.homeModel == null)
     {
         return;
     }
     try
     {
         List <AlexaEndpoint> endpoints = new List <AlexaEndpoint>();
         foreach (var c in this.homeModel.Controls)
         {
             AlexaEndpoint ep = ParseControlToEndpoint(c);
             if (ep != null)
             {
                 endpoints.Add(ep);
             }
         }
         this.cache = new AlexaDiscoverResponsePayload()
         {
             Endpoints = endpoints.ToArray()
         };
         LogLevel cacheinfoLogLevel = LogLevel.DebugLevel;
         if (this.lastDayCacheinfoLogged != DateTime.Today)
         {
             cacheinfoLogLevel           = LogLevel.InfoLevel;
             this.lastDayCacheinfoLogged = DateTime.Today;
         }
         log.Log(cacheinfoLogLevel, "Caching Alexa Discovery Response with {0} endpoints", this.cache.Endpoints.Length);
     }
     catch (Exception ex)
     {
         string errMsg = $"Failed to build discovery response: {ex.Message}";
         log.Error(ex, errMsg);
     }
 }
Пример #8
0
        public RandomLoggerActor(string name, TimeSpan minPeriod, TimeSpan maxPeriod, params string[] logTopics)
        {
            _random    = new Random();
            _logTopics = logTopics;
            _logger    = Context.WithIdentity(name);
            _minPeriod = minPeriod;
            _maxPeriod = maxPeriod;


            Receive <LogSomething>(msg =>
            {
                var time = DateTime.UtcNow;

                var level    = _random.Choose(Enum.GetValues(typeof(LogLevel)).Cast <LogLevel>());
                var template = "{Guid} {Value} {Time} {TimeSinceLastMessage}";
                var guid     = Guid.NewGuid();
                var value    = _random.Next();
                var timeDiff = (time - msg.Sent).TotalMilliseconds;


                _logger.Log(
                    level,
                    template,
                    guid,
                    value,
                    time,
                    timeDiff
                    );

                _mediator.Tell(new Publish("Logs", $"{guid} {value} {time} {timeDiff}"));

                ScheduleNext();
            });

            ScheduleNext();
        }
 /// <summary>Logs a message with a specified level.</summary>
 /// <param name="logLevel">The level used to log the message.</param>
 /// <param name="format">The message that is being logged.</param>
 /// <param name="args">An optional list of items used to format the message.</param>
 public virtual void Log(LogLevel logLevel, string format, params object[] args)
 {
     adapter.Log(logLevel, format, BuildArgs(args));
 }