Exemplo n.º 1
0
        private IMongoQueryable <Entity.InfoLog> CreatQueryAble(LogQuery query)
        {
            var collection = DbProvider.Collection <Entity.InfoLog>();
            var queryAble  = collection.AsQueryable().Where(a => 1 == 1);

            if (!string.IsNullOrEmpty(query.Content))
            {
                queryAble = queryAble.Where(a => a.Content.Contains(query.Content));
            }
            if (query.CreatTimeFrom.HasValue)
            {
                queryAble = queryAble.Where(a => a.CreationTime >= query.CreatTimeFrom);
            }
            if (query.CreatTmeTo.HasValue)
            {
                queryAble = queryAble.Where(a => a.CreationTime <= query.CreatTmeTo);
            }
            if (!string.IsNullOrEmpty(query.PlatformId))
            {
                queryAble = queryAble.Where(a => a.PlatformId == new ObjectId(query.PlatformId));
            }
            if (!string.IsNullOrEmpty(query.BusinessPosition))
            {
                queryAble = queryAble.Where(a => a.BusinessPosition.Contains(query.BusinessPosition));
            }
            if (!string.IsNullOrEmpty(query.TraceInfo))
            {
                queryAble = queryAble.Where(a => a.TraceInfo.Contains(query.TraceInfo));
            }
            return(queryAble);
        }
        public async Task <IActionResult> GetLogs([FromQuery] LogQuery urlQuery)
        {
            var result = new PaginatedResult <LogDTO>()
            {
                StatusCode = HttpStatusCode.OK
            };

            try
            {
                result = await _logRepository.GetLogs(urlQuery);

                if (result.IsFailure)
                {
                    return(BadRequest(result));
                }
            }
            catch (Exception ex)
            {
                result.StatusCode = HttpStatusCode.InternalServerError;
                result.AddError("Error on GetLogs", ex.Message, GetType().FullName);

                return(StatusCode((int)HttpStatusCode.InternalServerError, result));
            }

            return(Ok(result));
        }
Exemplo n.º 3
0
        public async Task SaveQueryAsync_saves_query()
        {
            // Arrange
            var db = Guid.NewGuid().ToString();

            InitializeDatabse(db);
            var settingsMoq = new Mock <ISejilSettings>();

            settingsMoq.SetupGet(p => p.SqliteDbPath).Returns(db);
            var repository = new SejilRepository(new SejilSqlProvider(settingsMoq.Object), settingsMoq.Object);

            var logQuery = new LogQuery
            {
                Id    = 1,
                Name  = "Test",
                Query = "q"
            };

            // Act
            var result = await repository.SaveQueryAsync(logQuery);

            // Assert
            Assert.True(result);
            var savedQueries = await repository.GetSavedQueriesAsync();

            Assert.Single(savedQueries);
            Assert.Equal(1, savedQueries.First().Id);
            Assert.Equal("Test", savedQueries.First().Name);
            Assert.Equal("q", savedQueries.First().Query);
        }
Exemplo n.º 4
0
        public async Task <PaginatedResult <LogDTO> > GetLogs(LogQuery urlQuery)
        {
            var query = GetLogs();

            if (!string.IsNullOrWhiteSpace(urlQuery.Title))
            {
                query = query.Where(x => x.Title == urlQuery.Title);
            }

            if (urlQuery.Level.HasValue)
            {
                query = query.Where(x => x.Level == urlQuery.Level);
            }

            if (!string.IsNullOrWhiteSpace(urlQuery.Origin))
            {
                query = query.Where(x => x.Origin == urlQuery.Origin);
            }

            if (urlQuery.UserId > 0)
            {
                query = query.Where(x => x.User.Id == urlQuery.UserId);
            }

            query.OrderByDescending(x => x.CreationDate);

            var totalItems = await query.LongCountAsync();

            query = query.Skip(urlQuery.PageSize * urlQuery.PageIndex)
                    .Take(urlQuery.PageSize);

            var logs = await query.ToListAsync();

            return(new PaginatedResult <LogDTO>(logs.Select(x => new LogDTO(x)), urlQuery.PageIndex, urlQuery.PageSize, totalItems));
        }
        private void AnalysisLogQuery(LogQuery logQuery, KeyValuePair <string, JToken> token, Action <List <LogQuery>, KeyValuePair <string, JToken> > action)
        {
            switch (logQuery.ObjectType)
            {
            case LogObjectType.jobject:
                var objectData = (JObject)token.Value;
                foreach (var objectItem in objectData)
                {
                    action(logQuery.Childrens, objectItem);
                }
                break;

            case LogObjectType.jarray:
                var datas = (JArray)token.Value;
                foreach (var item in datas)
                {
                    switch (GetTokenValueType(item))
                    {
                    case JTokenType.Object:
                        var arrayData = (JObject)item;
                        foreach (var arrayItem in arrayData)
                        {
                            action(logQuery.Childrens, arrayItem);
                        }
                        break;

                    default:
                        logQuery.PropertyType = GetJsType(item.Type);
                        break;
                    }
                }
                break;
            }
        }
Exemplo n.º 6
0
        public async Task <IResultList <LogEntry> > QueryAsync(string appId, LogQuery query, CancellationToken ct)
        {
            var filters = new List <FilterDefinition <MongoDbLogEntry> >
            {
                Filter.Eq(x => x.Entry.AppId, appId)
            };

            if (!string.IsNullOrWhiteSpace(query.Query))
            {
                var regex = new BsonRegularExpression(query.Query, "i");

                filters.Add(Filter.Regex(x => x.Entry.Message, regex));
            }

            var filter = Filter.And(filters);

            var taskForItems = Collection.Find(filter).ToListAsync(query, ct);
            var taskForCount = Collection.Find(filter).CountDocumentsAsync(ct);

            await Task.WhenAll(
                taskForItems,
                taskForCount);

            return(ResultList.Create(taskForCount.Result, taskForItems.Result.Select(x => x.ToEntry())));
        }
Exemplo n.º 7
0
        public override void Execute(Guid application)
        {
            try
            {
                var query = new LogQuery()
                {
                    ApplicationIdentifier = application,
                    From = DateTime.UtcNow.AddHours(-24),
                    To   = DateTime.UtcNow,
                    Top  = 5000
                };

                var data = new PerformanceData()
                {
                    Occurrences = logCore.SelectOccurrences(query),
                    GeneratedOn = DateTime.UtcNow,
                };

                foreach (var occurrence in data.Occurrences)
                {
                    occurrence.Token = null;
                }

                var objectId = LogCore.Performance1DaysFormat.FormatWithCulture(application.ToAscii85().GetHexMD5());
                blob.Save(objectId, data);
            }
            catch (Exception ex)
            {
                logCore.Log(ex, EventTypes.Critical, 99999);
            }
        }
Exemplo n.º 8
0
        public void FilterTop()
        {
            var list = new List <MessageDisplay>();
            var msg  = new MessageDisplay();

            msg.Fill();
            msg.OccurredOn = new DateTime(2000, 01, 01);
            list.Add(msg);

            msg = new MessageDisplay();
            msg.Fill();
            msg.OccurredOn = new DateTime(2012, 01, 01);
            list.Add(msg);

            var query = new LogQuery();

            query.Initialize();
            query.Top = 1;
            var filtered = query.Filter <MessageDisplay>(list);

            Assert.AreEqual <int>(1, filtered.Count());
            var item = filtered.First();

            Assert.AreEqual <Guid>(msg.Identifier, item.Identifier);
        }
Exemplo n.º 9
0
        public override void Execute(Guid application)
        {
            try
            {
                var query = new LogQuery()
                {
                    ApplicationIdentifier = application,
                    From = DateTime.UtcNow.AddHours(-24),
                    To   = DateTime.UtcNow,
                    Top  = 10000
                };

                var data = new CollectorData()
                {
                    Statistics  = logCore.SelectServerStatistics(query),
                    GeneratedOn = DateTime.UtcNow,
                };

                foreach (var stat in data.Statistics)
                {
                    stat.Token = null;
                }

                var objectId = LogCore.CollectorBrief1DaysFormat.FormatWithCulture(application.ToAscii85().GetHexMD5());
                blob.Save(objectId, data);
            }
            catch (Exception ex)
            {
                logCore.Log(ex, EventTypes.Critical, 99999);
            }
        }
        public QueryResult <Log> GetLogs(LogQuery queryObj)
        {
            DeleteOlderLogs(_context);

            var result = new QueryResult <Log>();

            var query = _context.Logs.ToList().AsQueryable();

            query = SortLogs(queryObj, query);

            var columnsMap = new Dictionary <string, Expression <Func <Log, object> > >()
            {
                ["message"]   = l => l.Message,
                ["level"]     = l => l.Level,
                ["timeStamp"] = l => l.TimeStamp
            };

            query = query.ApplyOrdering(queryObj, columnsMap);

            result.TotalItems = query.Count();

            query = query.ApplyPaging(queryObj);

            result.Items = query.ToList();

            return(result);
        }
Exemplo n.º 11
0
        public void FilterOrder()
        {
            var list = new List <MessageDisplay>();
            var msg  = new MessageDisplay();

            msg.Fill();
            msg.OccurredOn = new DateTime(2012, 01, 01);
            list.Add(msg);

            msg = new MessageDisplay();
            msg.Fill();
            msg.OccurredOn = new DateTime(2000, 01, 01);
            list.Add(msg);

            var query = new LogQuery();

            query.Initialize();
            var filtered = query.Filter <MessageDisplay>(list);

            Assert.AreEqual <int>(2, filtered.Count());
            var first = filtered.First();
            var last  = filtered.Last();

            Assert.IsTrue(first.OccurredOn > last.OccurredOn);
        }
Exemplo n.º 12
0
        public void LatestServerStatisticsDeep()
        {
            var source = new LogCore();
            var appId  = Guid.NewGuid();
            var server = Guid.NewGuid().ToString();
            ServerStatisticSet data = null;

            for (var i = 0; i < 4; i++)
            {
                data             = this.ServerStat(appId);
                data.MachineName = server;
                source.Log(data);
            }

            Assert.IsNotNull(data);

            var query = new LogQuery()
            {
                ApplicationIdentifier = appId,
                Deep = true,
            };

            var results = source.LatestServerStatistics(query);

            Assert.IsNotNull(results, "Result should not be null.");
            Assert.AreEqual <int>(1, results.Count());
            var result = results.FirstOrDefault();

            Assert.IsNotNull(result, "Result should not be null.");
            Assert.AreEqual <double>(data.CpuUsagePercentage, result.CpuUsagePercentage);
            Assert.AreEqual <double>(data.MemoryUsagePercentage, result.MemoryUsagePercentage);
            Assert.AreEqual <double>(data.PhysicalDiskUsagePercentage, result.PhysicalDiskUsagePercentage);
            Assert.AreEqual <string>(data.MachineName, result.MachineName);
            Assert.AreEqual <int>(4, result.Range.Count());
        }
Exemplo n.º 13
0
        public void SearchServerStatistics()
        {
            var source = new LogCore();
            var appId  = Guid.NewGuid();

            for (var i = 0; i < 4; i++)
            {
                var data = this.ServerStat(appId);

                source.Log(data);
            }

            var query = new LogQuery()
            {
                ApplicationIdentifier = appId,
                Top = 1,
            };

            var datas = source.SelectServerStatistics(query);

            Assert.IsNotNull(datas, "data should not be null.");
            Assert.AreEqual <int>(1, datas.Count(), "1 Should be contained.");

            query.Top = 3;

            datas = source.SelectServerStatistics(query);
            Assert.IsNotNull(datas, "data should not be null.");
            Assert.AreEqual <int>(3, datas.Count(), "3 Should be contained.");
        }
Exemplo n.º 14
0
        public void SearchMessages()
        {
            var  source = new LogCore();
            Guid appId  = Guid.NewGuid();

            for (int i = 0; i < 4; i++)
            {
                var data = this.Message(appId);

                source.Log(data);
            }

            var query = new LogQuery()
            {
                ApplicationIdentifier = appId,
                Top = 1,
            };

            var messages = source.SelectMessages(query);

            Assert.IsNotNull(messages, "Message data should not be null.");
            Assert.AreEqual <int>(1, messages.Count(), "1 Message Should be contained.");

            query.Top = 3;

            messages = source.SelectMessages(query);
            Assert.IsNotNull(messages, "Message data should not be null.");
            Assert.AreEqual <int>(3, messages.Count(), "3 Message Should be contained.");
        }
Exemplo n.º 15
0
        public void SearchOccurrences()
        {
            var  source = new LogCore();
            Guid appId  = Guid.NewGuid();

            for (int i = 0; i < 4; i++)
            {
                var data = this.Occurrence(appId);

                source.Log(data);
            }

            var query = new LogQuery()
            {
                ApplicationIdentifier = appId,
                Top = 1,
            };

            var occurrences = source.SelectOccurrences(query);

            Assert.IsNotNull(occurrences, "Error data should not be null.");
            Assert.AreEqual <int>(1, occurrences.Count(), "1 Error Should be contained.");

            query.Top = 3;

            occurrences = source.SelectOccurrences(query);
            Assert.IsNotNull(occurrences, "Error data should not be null.");
            Assert.AreEqual <int>(3, occurrences.Count(), "3 Error Should be contained.");
        }
Exemplo n.º 16
0
 public static void Fill(this LogQuery query)
 {
     query.From = DateTime.UtcNow.AddYears(-1);
     query.To   = DateTime.UtcNow;
     query.Top  = 100;
     query.ApplicationIdentifier = Guid.NewGuid();
 }
Exemplo n.º 17
0
        public ActionResult Error(Guid?application, DateTime?from, DateTime?to, int?top)
        {
            using (new PerformanceMonitor())
            {
                if (Guid.Empty == application || null == application)
                {
                    return(this.Json(WebResponse.Bind((int)Fault.InvalidApplicationIdentifier, "Application Identifier not specified."), JsonRequestBehavior.AllowGet));
                }
                else
                {
                    var query = new LogQuery()
                    {
                        ApplicationIdentifier = application.Value,
                        From = from ?? DateTime.UtcNow.AddDays(-21),
                        To   = to ?? DateTime.UtcNow,
                        Top  = top ?? MaxTop,
                    };

                    try
                    {
                        return(this.Json(logCore.SelectErrors(query), JsonRequestBehavior.AllowGet));
                    }
                    catch (Exception ex)
                    {
                        logCore.Log(ex, EventTypes.Error, (int)Fault.Unknown);
                        return(this.Json(WebResponse.Bind((int)Fault.Unknown, ex.Message), JsonRequestBehavior.AllowGet));
                    }
                }
            }
        }
        private void GetLogQueriesByLogProperties(Log log)
        {
            var properties = GetLogProperties(log);

            foreach (var property in properties)
            {
                if (!QueryGenerator.GetIsExistQueryByName(_logQueries, property.Name) &&
                    !GetIsBsonDocumentType(property.PropertyType))
                {
                    var query = new LogQuery(property.Name);
                    query.PropertyType = GetCsharptType(property.PropertyType);
                    _logQueries.Add(query);
                }
                else if (GetIsBsonDocumentType(property.PropertyType))
                {
                    if (QueryGenerator.GetIsExistQueryByName(_logQueries, property.Name))
                    {
                        var documents = property.GetValue(log) as BsonDocument;
                        var existData = _logQueries.SingleOrDefault(item => item.Key == property.Name);
                        QueryGenerator.ProcessExistLogQuery(existData, documents);
                    }
                    else
                    {
                        var documents = property.GetValue(log) as BsonDocument;
                        var query     = QueryGenerator.CreateLogQueryFromBsonDocument(property.Name, documents);
                        _logQueries.Add(query);
                    }
                }
            }
        }
        async Task <IList <LogData> > GetLogInformation1(LogQuery logQuery)
        {
            if (logQuery == null)
            {
                return(new List <LogData>());
            }
            using (var context = new DotNetLogEntities("name=DotNetLogEntities" + logQuery.Environment))
            {
                var result = await context.LogDetails
                             .Where(l => l.Level == logQuery.Level)
                             .Where(s => !string.IsNullOrEmpty(s.StartDateTime) &&
                                    s.StartDateTime.CompareTo(logQuery.StartDateTime) >= 0)
                             .Where(e => e.EndDateTime != null && e.EndDateTime <= logQuery.EndDateTime)
                             .Where(u => u.Url.Contains(logQuery.Application))
                             .ToArrayAsync();

                return(result.Select(r => new LogData()
                {
                    CustomerSessionId = context.LogMains.FirstOrDefault(c => c.LogId == r.LogId).CustomerSessionID,
                    StartDateTime = r.StartDateTime,
                    EndDateTime = r.EndDateTime,
                    CurrentUrl = r.Url,
                    UrlReferrrer = r.UrlReferrer,
                    Exception = r.Exception
                })
                       .OrderByDescending(o => o.StartDateTime)
                       .ToList());
            }
        }
Exemplo n.º 20
0
        public async Task <IResultList <LogEntry> > QueryAsync(string appId, LogQuery query, CancellationToken ct)
        {
            var filters = new List <FilterDefinition <MongoDbLogEntry> >
            {
                Filter.Eq(x => x.Entry.AppId, appId)
            };

            if (!string.IsNullOrWhiteSpace(query.Query))
            {
                var regex = new BsonRegularExpression(query.Query, "i");

                filters.Add(Filter.Regex(x => x.Entry.Message, regex));
            }

            var filter = Filter.And(filters);

            var resultItems = await Collection.Find(filter).ToListAsync(query, ct);

            var resultTotal = (long)resultItems.Count;

            if (query.ShouldQueryTotal(resultItems))
            {
                resultTotal = await Collection.Find(filter).CountDocumentsAsync(ct);
            }

            return(ResultList.Create(resultTotal, resultItems.Select(x => x.ToEntry())));
        }
Exemplo n.º 21
0
        internal static LogSearchCursor GetCursor(string server, ServerVersion version, string logFile, string messageId, ProxyAddressCollection senderProxyAddresses, DateTime startTime, DateTime endTime)
        {
            LogQuery        logQuery        = new LogQuery();
            LogAndCondition logAndCondition = new LogAndCondition();

            if (!string.IsNullOrEmpty(messageId))
            {
                LogCondition fieldStringComparison = TrackingSearch.GetFieldStringComparison(MessageTrackingField.MessageId, CsvFieldCache.NormalizeMessageID(messageId));
                logAndCondition.Conditions.Add(fieldStringComparison);
            }
            if (senderProxyAddresses != null)
            {
                LogOrCondition logOrCondition = new LogOrCondition();
                foreach (ProxyAddress proxyAddress in senderProxyAddresses)
                {
                    LogCondition fieldStringComparison2 = TrackingSearch.GetFieldStringComparison(MessageTrackingField.SenderAddress, proxyAddress.AddressString);
                    logOrCondition.Conditions.Add(fieldStringComparison2);
                }
                logAndCondition.Conditions.Add(logOrCondition);
            }
            logQuery.Filter    = logAndCondition;
            logQuery.Beginning = startTime;
            logQuery.End       = endTime;
            return(new LogSearchCursor(MessageTrackingSchema.MessageTrackingEvent, server, version, logFile, logQuery, null));
        }
Exemplo n.º 22
0
        /// <summary>
        /// Gets all action log.
        /// </summary>
        /// <param name="totalRecords">The total records.</param>
        /// <param name="currentPage">The current page.</param>
        /// <param name="pageSize">Size of the page.</param>
        /// <param name="sortBy">The sort by.</param>
        /// <param name="descending">if set to <c>true</c> [descending].</param>
        /// <param name="loginName">The login name.</param>
        /// <param name="actionContent">Action Content.</param>
        /// <param name="actionType">Action Type.</param>
        /// <returns></returns>
        public IEnumerable <ActionLog> GetAllActionLogItems(out int totalRecords,
                                                            int currentPage          = 1,
                                                            int pageSize             = 25,
                                                            bool descending          = true,
                                                            string sortBy            = "ActionTime",
                                                            string loginName         = "",
                                                            string actionContent     = "",
                                                            LogActionType?actionType = null)
        {
            var spec = LogQuery.WithAllAct();

            spec         = !string.IsNullOrEmpty(loginName) ? spec.And(LogQuery.WithLoginNameAct(loginName)) : spec;
            spec         = !string.IsNullOrEmpty(actionContent) ? spec.And(LogQuery.WithActionContentAct(actionContent)) : spec;
            spec         = actionType.HasValue ? spec.And(LogQuery.WithActionTypeAct(actionType.Value)) : spec;
            totalRecords = _actionLog.Count(spec);
            var sort = Context.Filters.Sort <ActionLog, DateTime>(al => al.ActionTime, true);

            switch (sortBy)
            {
            case "LoginName":
                sort = Context.Filters.Sort <ActionLog, string>(al => al.LoginName, descending);
                break;

            case "ActionContent":
                sort = Context.Filters.Sort <ActionLog, string>(al => al.ActionContent, descending);
                break;

            case "ActionTime":
                sort = Context.Filters.Sort <ActionLog, DateTime>(al => al.ActionTime, descending);
                break;
            }
            var pager = Context.Filters.Page <ActionLog>(currentPage, pageSize);

            return(_actionLog.Find(spec, sort, pager));
        }
Exemplo n.º 23
0
        public LogQuery CreateLogQueryFromBsonDocument(string propertyName, BsonDocument bsonElements)
        {
            var jOject = JObject.Parse(bsonElements.ToJson());
            var query  = new LogQuery(propertyName);

            switch (GetTokenValueType(jOject))
            {
            case JTokenType.Object:
                query.ObjectType = LogObjectType.jobject;
                foreach (var model in jOject)
                {
                    query.Childrens.Add(CreateLogQuery(model));
                }
                break;

            case JTokenType.Array:
                query.ObjectType = LogObjectType.jarray;
                foreach (var mdel in jOject)
                {
                    query.Childrens.Add(CreateLogQuery(mdel));
                }
                break;
            }
            return(query);
        }
        public void Query()
        {
            var table = new AzureTable <MessageData>(CloudStorageAccount.DevelopmentStorageAccount);

            var appId = Guid.NewGuid();

            for (int i = 0; i < 4; i++)
            {
                var data = new MessageData(appId);
                data.Fill();

                table.AddEntity(data);
            }

            var query = new LogQuery()
            {
                ApplicationIdentifier = appId,
                From = DateTime.UtcNow.AddMinutes(-1),
                To   = DateTime.UtcNow.AddMilliseconds(1),
                Top  = 1,
            };

            var messages = table.Query <MessageData>(query).ToList();

            Assert.IsNotNull(messages, "Message data should not be null.");
            Assert.AreEqual <int>(1, messages.Count(), "1 Message Should be contained.");

            query.Top = 3;

            messages = table.Query <MessageData>(query).ToList();
            Assert.IsNotNull(messages, "Message data should not be null.");
            Assert.AreEqual <int>(3, messages.Count(), "3 Message Should be contained.");
        }
Exemplo n.º 25
0
        private CompressedErrors Compress(Guid applicationIdentifier)
        {
            var compressed = new CompressedErrors()
            {
                GeneratedOn = DateTime.UtcNow,
            };

            var query = new LogQuery()
            {
                ApplicationIdentifier = applicationIdentifier,
                From = DateTime.UtcNow.AddDays(-1),
                To   = DateTime.UtcNow,
            };

            try
            {
                var data = logCore.SelectErrors(query);

                compressed.Errors      = this.Compressed(data);
                compressed.Errors      = this.ErrorRate(data, compressed.Errors);
                compressed.Occurrences = this.Occurrences(data, compressed.Errors);
            }
            catch (Exception ex)
            {
                logCore.Log(ex, EventTypes.Critical, 99999);
            }

            return(compressed);
        }
Exemplo n.º 26
0
        public Expression <Func <InfoLog, bool> > CreatCondition(LogQuery logQuery)
        {
            var condition = LinqExtension.True <InfoLog>();

            if (!string.IsNullOrEmpty(logQuery.Content))
            {
                condition.And(a => a.Content.Contains(logQuery.Content));
            }
            if (logQuery.CreatTimeFrom.HasValue)
            {
                condition.And(a => a.CreationTime >= logQuery.CreatTimeFrom);
            }
            if (logQuery.CreatTmeTo.HasValue)
            {
                condition.And(a => a.CreationTime >= logQuery.CreatTmeTo);
            }
            if (!string.IsNullOrEmpty(logQuery.PlatformId))
            {
                condition.And(a => a.PlatformId == new ObjectId(logQuery.PlatformId));
            }
            if (!string.IsNullOrEmpty(logQuery.BusinessPosition))
            {
                condition.And(a => $".{a.BusinessPosition}.".Contains($".{logQuery.BusinessPosition}."));
            }
            if (!string.IsNullOrEmpty(logQuery.TraceInfo))
            {
                condition.And(a => a.TraceInfo.Contains(logQuery.TraceInfo));
            }
            return(condition);
        }
Exemplo n.º 27
0
        /// <summary>
        /// Digest Errors
        /// </summary>
        /// <param name="applicationIdentifier">Application Identifier</param>
        /// <returns>History</returns>
        public LogHistory <ErrorDisplay> DigestErrors(Guid applicationIdentifier)
        {
            Contract.Requires <ArgumentException>(Guid.Empty != applicationIdentifier);
            Contract.Ensures(Contract.Result <LogHistory <ErrorDisplay> >() != null);

            var query = new LogQuery()
            {
                From = DateTime.UtcNow.AddDays(-7),
                Top  = 50000,
                ApplicationIdentifier = applicationIdentifier,
                Deep = true,
            };

            var history = new LogHistory <ErrorDisplay>();

            try
            {
                history = this.Digest <ErrorDisplay>(this.SelectErrors(query), Error21DaysFormat.FormatWithCulture(applicationIdentifier));
            }
            catch (Exception ex)
            {
                this.Log(ex, EventTypes.Error, (int)ServiceFault.PerformanceDigest);
            }

            return(history);
        }
Exemplo n.º 28
0
        public void GetServerStatistic()
        {
            var source = new LogCore();
            var appId  = Guid.NewGuid();

            for (var i = 0; i < 4; i++)
            {
                var data = this.ServerStat(appId);

                source.Log(data);
            }

            var query = new LogQuery()
            {
                ApplicationIdentifier = appId,
                Top = 1,
            };

            var items = source.SelectServerStatistics(query);

            var item = items.First();

            query.Identifier = item.Identifier;

            var returnedItems = source.SelectServerStatistics(query);

            Assert.AreEqual <int>(1, returnedItems.Count());
            var returned = returnedItems.First();

            Assert.AreEqual <Guid>(item.Identifier, returned.Identifier);
        }
Exemplo n.º 29
0
        public IEnumerable <ServerStatisticSetDisplay> LatestServerStatistics(LogQuery query)
        {
            Contract.Requires <ArgumentNullException>(null != query);
            Contract.Requires <ArgumentException>(Guid.Empty != query.ApplicationIdentifier, "Application Identifier is empty.");

            Contract.Ensures(Contract.Result <IEnumerable <ServerStatisticSet> >() != null);

            using (new PerformanceMonitor())
            {
                var results = (from d in this.latestServerStatisticsTable.QueryByPartition(query.ApplicationIdentifier.ToString())
                               where d.OccurredOn > DateTime.UtcNow.AddMinutes(-10)
                               select d).ToList().Select(d => d.Convert());
                var items = new List <ServerStatisticSetDisplay>(results);

                if (query.Deep.HasValue && query.Deep.Value)
                {
                    var start        = query.From.HasValue ? query.From.Value : DateTime.UtcNow.AddDays(-1);
                    var dailyResults = (from d in this.serverStatisticsTable.QueryByPartition(query.ApplicationIdentifier.ToString())
                                        where d.OccurredOn > start
                                        select d).ToList();

                    for (int i = 0; i < items.Count(); i++)
                    {
                        items[i].Range = (from d in dailyResults
                                          where string.Equals(d.MachineName, items[i].MachineName, StringComparison.OrdinalIgnoreCase)
                                          select d.Convert()).ToList();
                    }
                }

                return(items);
            }
        }
Exemplo n.º 30
0
        public IEnumerable <ServerStatisticSetDisplay> SelectServerStatistics(LogQuery query)
        {
            Contract.Requires <ArgumentNullException>(null != query);
            Contract.Requires <ArgumentException>(Guid.Empty != query.ApplicationIdentifier, "Application Identifier is empty.");

            Contract.Ensures(Contract.Result <IEnumerable <ServerStatisticSet> >() != null);

            using (new PerformanceMonitor())
            {
                query.Initialize();
                var start = query.From.Value;
                var end   = query.To.Value;

                if (query.IsUnique)
                {
                    var list = new List <ServerStatisticSetDisplay>();
                    var item = this.serverStatisticsTable.Get <ServerStatisticSetDisplay, ServerStatisticsRow>(query.PartitionKey, query.RowKey);
                    if (null != item)
                    {
                        list.Add(item);
                    }

                    return(list);
                }
                else
                {
                    var results = this.serverStatisticsTable.QueryBy(d => d.PartitionKey == query.PartitionKey && d.Timestamp > start && d.Timestamp < end, query.Top.Value);
                    return(results.ToList().AsParallel().Select(d => d.Convert()));
                }
            }
        }
Exemplo n.º 31
0
        public async Task<bool> HandleAsync(LogQuery e)
        {
            await e.ReplyAsync(await (from entry in Context.Entries.Query()
                               where entry.LoggedAt > e.LoggedAfter
                               where entry.LoggedAt < e.LoggedBefore
                               orderby entry.LoggedAt descending
                               select new LogEntry
                               {
                                   UserId = entry.UserId,
                                   LoggedAt = entry.LoggedAt,
                                   Text = entry.Text,
                                   Error = entry.Error,
                                   Xml = entry.Xml
                               })
                   .Skip(e.PageSize * (e.Page - 1))
                   .Take(e.PageSize)
                   .ToArrayAsync());

            return true;
        }
Exemplo n.º 32
0
        public LogResultSet Query(LogQuery criteria)
        {
            var result = new LogResultSet();
            result.TotalEntries = Reader.Count(criteria);
            if (criteria.PageSize == 0) {
                criteria.PageNumber = 1;
                criteria.PageSize = result.TotalEntries;
            }

            result.PageSize = criteria.PageSize;
            result.TotalPages = (result.TotalEntries + result.PageSize - 1) / result.PageSize;
            result.Page = criteria.PageNumber;
            if (result.Page < 1) result.Page = 1;
            if (result.Page > result.TotalPages) result.Page = result.TotalPages;
            if (result.Page >= 1)
                result.LogEntries = Reader.GetLogEntries(criteria)
                    .Skip((result.Page - 1) * result.PageSize)
                    .Take(result.PageSize).ToList();
            else
                result.LogEntries = new List<LogEntry>(0);
            return result;
        }