예제 #1
0
        public static bool Execute(string line, KLog uploaderLog)
        {
            var cleanLine = line.Replace("#KLOG_INSTANCE_STATUS#", "");

            cleanLine = cleanLine.Replace("KLOG_VERSION_", "");

            InstanceModel instanceHeader;

            try
            {
                instanceHeader = JsonConvert.DeserializeObject <InstanceModel>(cleanLine);

                var checkAddInstanceStart = DataAccessor.AddInstanceStart(instanceHeader);

                if (!checkAddInstanceStart.Success)
                {
                    uploaderLog.Error($"SQL Expection on [UploadFirstLine].[AddInstanceStart] - Message: {checkAddInstanceStart.Message}");
                    return(false);
                }
            }
            catch (Exception ex)
            {
                uploaderLog.Error($"Expection on [UploadFirstLine].[DeserializeInstanceHeader] - Message: {ex.ToString()}");
                return(false);
            }

            return(true);
        }
예제 #2
0
        public static bool Execute(string line, KLog uploaderLog)
        {
            var cleanLine = line.Replace("#KLOG_INSTANCE_STATUS#", "");

            InstanceModel instanceHeader = null;

            try
            {
                instanceHeader = JsonConvert.DeserializeObject <InstanceModel>(cleanLine);
            }
            catch (Exception ex)
            {
                uploaderLog.Error($"Expection on [UploadLastLine].[DeserializeInstanceFooter] - Message: {ex.ToString()}");
                return(false);
            }

            var checkUpdateInstanceStop = DataAccessor.UpdateInstanceStop(instanceHeader);

            if (!checkUpdateInstanceStop.Success)
            {
                uploaderLog.Error($"SQL Expection on [UploadLastLine].[UpdateInstanceStop] - Message: {checkUpdateInstanceStop.Message}");
                return(false);
            }

            return(true);
        }
예제 #3
0
        /// <summary>
        /// Query Kiroku Storage for a single KLOG.
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public static OkObjectResult Execute(HttpRequest req)
        {
            using (KLog klog = new KLog($"KQueryManager,Execute"))
            {
                if (!_configOnline)
                {
                    klog.Error("Config failed to load.");
                    return(new OkObjectResult(""));
                }

                if (req == null)
                {
                    klog.Warning("Request was empty.");
                    return(new OkObjectResult(""));
                }

                string id = req?.Query["id"];

                try
                {
                    Guid checkId = new Guid(id);

                    byte[] doc = Storage.GetLog(id);

                    var payload = Encoding.UTF8.GetString(doc, 0, doc.Length);

                    if (!string.IsNullOrEmpty(payload))
                    {
                        payload = payload.Replace("#KLOG_INSTANCE_STATUS#", "");

                        payload = payload.Replace("}", "},");

                        payload = "[" + payload + "]";

                        payload = payload.Replace("},\r\n$", "}]");

                        payload = JValue.Parse(payload).ToString(Formatting.Indented);
                    }

                    if (doc == null)
                    {
                        klog.Error($"Document is null. Id: {id}");
                    }

                    return(doc == null
                        ? new OkObjectResult($"404")
                        : new OkObjectResult(payload));
                }
                catch (Exception ex)
                {
                    klog.Error($"EXCEPTION : {ex.ToString()}");
                    return(new OkObjectResult(""));
                }
            }
        }
        public static void Execute()
        {
            // Blob retention
            using (KLog blobRetention = new KLog("BlobFileRetention-BlobRetention"))
            {
                try
                {
                    IEnumerable <BlobFileModel> retentionFileCollection = BlobFileCollection.CurrentRetentionCount();

                    blobRetention.Info($"Retention Count: {retentionFileCollection.Count()}");

                    foreach (BlobFileModel blobFile in retentionFileCollection)
                    {
                        // for each file, confim check one more
                        blobRetention.Info($"Retention => File Name: {blobFile.CloudFile}");

                        string cloudFile = blobFile.CloudFile;

                        try
                        {
                            BlobClient.DeleteBlobFile(cloudFile);

                            blobRetention.Info($"File Deleted => File Name: {blobFile.CloudFile}");
                        }
                        catch (Exception ex)
                        {
                            blobRetention.Error($"Delete Failure: {blobFile.CloudFile} Exception: {ex}");
                        }
                    }
                }
                catch (Exception ex)
                {
                    blobRetention.Error($"BlobFileRetention Exception: {ex.ToString()}");
                }
            }

            // SQL Retention
            using (KLog sqlRetention = new KLog("BlobFileRetention-SQLRetention"))
            {
                try
                {
                    SQLResponseModel checkRetention = DataAccessor.Retention(Configuration.RetentionDays);

                    if (!checkRetention.Success)
                    {
                        sqlRetention.Error($"SQL Expection on [BlobFileRetention].[Retention] - Message: {checkRetention.Message}");
                    }
                }
                catch (Exception ex)
                {
                    sqlRetention.Error($"BlobFileRetention Exception: {ex.ToString()}");
                }
            }
        }
예제 #5
0
        /// <summary>
        /// Method for getting the correct position for the user's entry.
        /// First available one if the user has no entry already.
        /// </summary>
        /// <param name="id">The ID of the user</param>
        /// <returns>The row number for the entry</returns>
        public static int GetEntryPos(ulong id)
        {
            int        i     = 2;
            ExcelRange cells = StrikeLog.Workbook.Worksheets[StrikeLogPage].Cells;

            while (cells["A" + i].Value != null)
            {
                ulong spot;

                if (!ulong.TryParse(cells[$"A{i}"].Value.ToString().Replace("'", ""), out spot))
                {
                    KLog.Error($"INVALID ID IN STRIKE LOG {cells[$"A{i}"].Value.ToString().Replace("'", "")}");
                    throw new Exception("Invalid Number.");
                }

                if (spot == id)
                {
                    return(i);
                }

                i++;
            }

            return(i);
        }
        public static void Execute()
        {
            using (KLog collectorLog = new KLog("ClassBlobFileCollector-MethodExecute"))
            {
                try
                {
                    var token = new BlobContinuationToken();

                    var blobCollection = BlobClient.BlobContainer.ListBlobsSegmentedAsync(null, token).GetAwaiter().GetResult();

                    List <string> blobPrefixNames = blobCollection.Results.OfType <CloudBlobDirectory>().Select(b => b.Prefix).ToList();

                    collectorLog.Info($"Collector => Prefix Count: {blobPrefixNames.Count()}");

                    // flush static object
                    BlobFileCollection.StaticFlush();

                    // for each dir in the blob container
                    foreach (var blobPrefixName in blobPrefixNames)
                    {
                        var prefixblobCollection = BlobClient.BlobContainer.ListBlobsSegmentedAsync(blobPrefixName, token).GetAwaiter().GetResult();

                        List <string> prefixblobFileNames = prefixblobCollection.Results.OfType <CloudBlockBlob>().Select(b => b.Name).ToList();

                        collectorLog.Info($"Collector => Parsing Prefix: {blobPrefixName}");

                        BlobFileParser.Execute(blobPrefixName, prefixblobFileNames);
                    }
                }
                catch (Exception ex)
                {
                    collectorLog.Error($"BlobFileCollector Exception: {ex.ToString()}");
                }
            }
        }
예제 #7
0
        /// <summary>
        /// Delete local "KLOG_A_$(guid).txt" files that exceed the provided retention period (in days).
        /// </summary>
        /// <param name="retentionFiles"></param>
        public static void Retention(IEnumerable <FileModel> retentionFiles)
        {
            using (KLog logRetention = new KLog("ClassProcessor-MethodRetention"))
            {
                try
                {
                    foreach (var retentionFile in retentionFiles)
                    {
                        // TODO: clean-up check + checkBool
                        var check = ((DateTime.UtcNow.AddDays(Configuration.RetentionDays)) < retentionFile.FileDate) ? "Hold" : "Delete";

                        var checkBool = ((DateTime.UtcNow.AddDays(Configuration.RetentionDays)) < retentionFile.FileDate);

                        logRetention.Info($"Retention File Operation => Time: {retentionFile.FileDate.ToString()}, Result: {check.ToString()}, File: {retentionFile.FileName}");

                        if (!checkBool)
                        {
                            File.Delete(retentionFile.FullPath);

                            logRetention.Info($"Retention File Operation => |- Delete File: {retentionFile.FileName}");
                        }
                    }
                }
                catch (Exception ex)
                {
                    logRetention.Error($"{ex.ToString()}");
                }
            }
        }
        public static bool Execute(string line, Guid fileGuid, KLog uploaderLog)
        {
            uploaderLog.Warning($"Uploader => Footer Check Failed - Guid: {fileGuid.ToString()}");

            BlobFileCollection.GetFiles().First(d => d.FileGuid == fileGuid).FooterStatus = false;

            LogRecordModel record = null;

            try
            {
                record = JsonConvert.DeserializeObject <LogRecordModel>(line);
            }
            catch (Exception ex)
            {
                uploaderLog.Error($" [UploadInstanceStop] Log Record Deserialize Exception: {ex.ToString()}");
                return(false);
            }

            var newEndTime = record.EventTime;

            InstanceModel newInstanceCloser = new InstanceModel();

            newInstanceCloser.InstanceID = fileGuid;
            newInstanceCloser.EventTime  = newEndTime;

            var checkUpdateInstaceClose = DataAccessor.UpdateInstanceStop(newInstanceCloser);

            if (!checkUpdateInstaceClose.Success)
            {
                uploaderLog.Error($"SQL Expection on [UploadInstanceStop].[UpdateInstaceClose] - Message: {checkUpdateInstaceClose.Message}");
                return(false);
            }

            var checkUpdateBlockStop = DataAccessor.UpdateBlockEmptyStop(record, fileGuid);

            if (!checkUpdateBlockStop.Success)
            {
                uploaderLog.Error($"SQL Expection on [UploadInstanceStop].[UpdateBlockStop] - Message: {checkUpdateBlockStop.Message}");
                return(false);
            }

            return(true);
        }
예제 #9
0
        public static void Execute()
        {
            using (KLog checkLog = new KLog("ClassBlobFileCheck-MethodExecute"))
            {
                try
                {
                    foreach (var file in BlobFileCollection.GetFiles())
                    {
                        if (file.FileGuid != Guid.Empty)
                        {
                            var resultResponse = DataAccessor.CheckInstanceId(file.FileGuid);

                            if (!resultResponse.Success)
                            {
                                checkLog.Error($"SQL Expection on [BlobFileCheck].[CheckInstance] - Message: {resultResponse.Message}");
                                break;
                            }

                            if (resultResponse.Id != Guid.Empty)
                            {
                                BlobFileCollection.GetFiles().First(d => d.FileGuid == file.FileGuid).Exist = true;
                                checkLog.Info($"Instance Check => Guid: {file.FileGuid.ToString()} Result: true");
                            }
                            else
                            {
                                BlobFileCollection.GetFiles().First(d => d.FileGuid == file.FileGuid).Exist = false;
                                checkLog.Info($"Instance Check => Guid: {file.FileGuid.ToString()} Result: false");
                            }
                        }
                        else
                        {
                            BlobFileCollection.GetFiles().First(d => d.FileGuid == file.FileGuid).Exist = true;
                            checkLog.Info($"Instance Check => Guid: {file.FileGuid.ToString()} Result: true (empty guid)");
                        }
                    }
                }
                catch (Exception ex)
                {
                    checkLog.Error($"BlobfileCheck Expection: {ex.ToString()}");
                }
            }
        }
예제 #10
0
        /// <summary>
        /// Delete local "KLOG_A_$(guid).txt" files that exceed the configured retention period (in days).
        /// </summary>
        /// <param name="retentionFiles"></param>
        public static void Execute()
        {
            using (KLog logRetention = new KLog("ClassDeleteLogs-MethodExecute"))
            {
                try
                {
                    if (Capsule.DeleteFileCount() > 0)
                    {
                        foreach (var retentionFile in Capsule.DeleteFiles)
                        {
                            // TODO: clean-up check + checkBool

                            if (Configuration.RetentionDays < 0)
                            {
                                var check     = ((DateTime.UtcNow.AddDays(Configuration.RetentionDays)) < retentionFile.FileDate) ? "Hold" : "Delete";
                                var checkBool = ((DateTime.UtcNow.AddDays(Configuration.RetentionDays)) < retentionFile.FileDate);

                                logRetention.Info($"Retention File Operation => Time: {retentionFile.FileDate.ToString()}, Result: {check.ToString()}, File: {retentionFile.FileName}");

                                if (!checkBool)
                                {
                                    File.Delete(retentionFile.FullPath);

                                    logRetention.Info($"Retention File Operation => |- Delete File: {retentionFile.FileName}");
                                }
                            }
                            else
                            {
                                File.Delete(retentionFile.FullPath);

                                logRetention.Info($"Retention File Operation => |- Delete File: {retentionFile.FileName}");
                            }
                        }
                    }
                    else
                    {
                        logRetention.Info("No files were marked for retention.");
                    }
                }
                catch (Exception ex)
                {
                    logRetention.Error($"{ex.ToString()}");
                }
            }
        }
        public static bool Execute(string line, List <LogRecordModel> recordModelList, KLog uploaderLog)
        {
            try
            {
                var record = JsonConvert.DeserializeObject <LogRecordModel>(line);

                if (CheckWriteByType(record.LogType))
                {
                    recordModelList.Add(record);
                }
            }
            catch
            {
                uploaderLog.Error($"Uploader [AddLogToCollection] => Line Exception: {line}");
                return(false);
            }

            return(true);
        }
예제 #12
0
        // this should pass in a single List<BlobFileModel>
        public static void Execute(string blobPrefixName, List <string> prefixblobFileNames)
        {
            using (KLog parserLog = new KLog("ClassBlobFileParser-MethodExecute"))
            {
                try
                {
                    foreach (var file in prefixblobFileNames)
                    {
                        var fileNameWithoutPrefix = file.Replace(blobPrefixName, "");

                        BlobFileModel blobFile = new BlobFileModel();
                        blobFile.File      = fileNameWithoutPrefix;
                        blobFile.CloudFile = file;

                        // Check and parse the full log file name
                        if (fileNameWithoutPrefix.Count() == 47 && fileNameWithoutPrefix.Contains("KLOG_"))
                        {
                            var parseGuid = Guid.Parse(fileNameWithoutPrefix.Substring(7, 36));
                            var parseTag  = fileNameWithoutPrefix.Substring(1, 6);

                            blobFile.FileGuid    = parseGuid;
                            blobFile.Tag         = parseTag;
                            blobFile.ParseStatus = true;

                            parserLog.Info($"Parser => File Name: {fileNameWithoutPrefix} Tag: {parseTag} Guid: {parseGuid}");
                        }
                        else
                        {
                            blobFile.ParseStatus = false;
                        }

                        BlobFileCollection.AddFile(blobFile);
                    }
                }
                catch (Exception ex)
                {
                    parserLog.Error($"BlobFileParser Exception: {ex.ToString()}");
                }
            }
        }
예제 #13
0
        /// <summary>
        /// Identify local "KLOG_W_$(guid).txt" files (orpahned) that exceed the configured retention period (in hours). The files are renamed (re-queued) to "KLOG_S_$(guid).txt" for sending.
        /// </summary>
        /// <param name="cleanupFiles"></param>
        public static void Execute()
        {
            using (KLog logCleanse = new KLog("ClassCleanseLogs-MethodExecute"))
            {
                try
                {
                    if (Capsule.CleanUpFileCount() > 0)
                    {
                        foreach (var cleanseFile in Capsule.CleanUpFiles)
                        {
                            // TODO: clean-up check + checkBool
                            var check = ((DateTime.UtcNow.AddHours(Configuration.CleanseHours)) < cleanseFile.FileDate) ? "Hold" : "Rename";

                            var checkBool = ((DateTime.UtcNow.AddHours(Configuration.CleanseHours)) < cleanseFile.FileDate);

                            logCleanse.Info($"Cleanse File Operation => Time: {cleanseFile.FileDate.ToString()}, Result: {check.ToString()}, File: {cleanseFile.FileName}");

                            if (!checkBool)
                            {
                                var renamefileName = cleanseFile.Path + @"\KLOG_S_" + cleanseFile.FileGuid.ToString() + ".txt";

                                File.Move(cleanseFile.FullPath, renamefileName);

                                logCleanse.Info($"Cleanse File Operation => |- Rename File: {renamefileName}");
                            }
                        }
                    }
                    else
                    {
                        logCleanse.Info("No files required clean-up.");
                    }
                }
                catch (Exception ex)
                {
                    logCleanse.Error($"{ex.ToString()}");
                }
            }
        }
예제 #14
0
        public static async Task AddTitle(SocketGuildUser user, int titleid)
        {
            if (!NodeMap.ContainsKey(titleid))
            {
                KLog.Error($"Attempted to give user {BotUtils.GetFullUsername(user)} invalid title ID #{titleid}");
                return;
            }

            TitleNode node = NodeMap[titleid];

            if (node == null)
            {
                KLog.Error($"Attempted to give user {BotUtils.GetFullUsername(user)} null title with ID #{titleid}");
                return;
            }

            UserDataNode u = UserDataManager.GetUserData(user);

            if (u.Titles == null)
            {
                u.Titles = new List <int>();
            }

            if (u.Titles.Contains(titleid))
            {
                return;                              // Don't give duplicate titles
            }
            u.Titles.Add(titleid);
            node.OnComplete(user);

            KLog.Important($"User {BotUtils.GetFullUsername(user)} has earned title {node.Name}");

            UserDataManager.SaveUserData();

            await AnnounceAchievement(user, node);
        }
예제 #15
0
        public static void Execute()
        {
            using (KLog uploaderLog = new KLog("ClassBlobFileUploader-MethodExecute"))
            {
                // Load files not currently uploaded
                var existFileCollction = BlobFileCollection.CurrentExistFalseCount();

                try
                {
                    foreach (var blobFile in existFileCollction)
                    {
                        try
                        {
                            // Set variables
                            var cloudFile   = blobFile.CloudFile;
                            var fileGuid    = blobFile.FileGuid;
                            var lineCounter = 1;

                            List <LogRecordModel> recordModelList = new List <LogRecordModel>();
                            List <string>         lines           = new List <string>();

                            var document = BlobClient.GetDocument(cloudFile);

                            lines = ReadFile.Execute(document);

                            var lineCountTotal = lines.Count();

                            uploaderLog.Info($"Uploader => Starting Upload - Guid: {fileGuid.ToString()} Line Count: {lineCountTotal} ");

                            //
                            // Read each line in the log file. Check first and last line for KLog instance data. Break loop on any unexcpted data or failure.
                            //
                            foreach (var line in lines)
                            {
                                //
                                // Check first line -- expecting the KLog instane "header"
                                //
                                if (lineCounter == 1)
                                {
                                    if (line.Contains("#KLOG_INSTANCE_STATUS#"))
                                    {
                                        var checkUploadFirstLine = UploadFirstLine.Execute(line, uploaderLog);

                                        if (!checkUploadFirstLine)
                                        {
                                            uploaderLog.Error($"[BlobFileUploader].[checkUploadFirstLine] - GUID: {fileGuid}");

                                            break;
                                        }
                                    }
                                    else
                                    {
                                        UploadFirstLine.MarkFailure(fileGuid);

                                        uploaderLog.Error($"Uploader => Header Check Failed - Guid: {fileGuid.ToString()} Line: {line}");

                                        break;
                                    }

                                    lineCounter++;
                                }

                                //
                                // Check last line -- expecting the KLog instance "footer" and add all logs.
                                //
                                else if (lineCounter == lineCountTotal)
                                {
                                    // Post all logs
                                    var checkUploadAllLogs = UploadAllLogs.Execute(recordModelList, fileGuid, uploaderLog);

                                    if (!checkUploadAllLogs)
                                    {
                                        uploaderLog.Error($"[BlobFileUploader].[UploadAllLogs] - GUID: {fileGuid}");
                                        break;
                                    }

                                    // Check for a proper KLog instance "footer"
                                    if (line.Contains("#KLOG_INSTANCE_STATUS#"))
                                    {
                                        var checkUploadLastLine = UploadLastLine.Execute(line, uploaderLog);

                                        if (!checkUploadLastLine)
                                        {
                                            uploaderLog.Error($"[BlobFileUploader].[UploadLastLine] - GUID: {fileGuid}");
                                        }
                                    }
                                    else
                                    {
                                        var checkUploadInstanceStop = UploadInstanceStop.Execute(line, fileGuid, uploaderLog);

                                        if (!checkUploadInstanceStop)
                                        {
                                            uploaderLog.Error($"[BlobFileUploader].[UploadInstanceStop] - GUID: {fileGuid}");
                                        }
                                    }

                                    uploaderLog.Info($"Log Loaded - Guid: {fileGuid.ToString()}");
                                }

                                //
                                // Check line for "normal" log record, add to collection to bulk add later.
                                //
                                else
                                {
                                    var checkAddLogToCollection = AddLogToCollection.Execute(line, recordModelList, uploaderLog);

                                    if (!checkAddLogToCollection)
                                    {
                                        uploaderLog.Error($"[BlobFileUploader].[AddLogToCollection] - GUID: {fileGuid}");
                                        break;
                                    }

                                    lineCounter++;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            uploaderLog.Error($"Blob Upload Failure - Exception: {ex}");
                        }
                    }
                }
                catch (Exception ex)
                {
                    uploaderLog.Error($"BlobFileUploader Exception: {ex}");
                }
            }
        }
예제 #16
0
        public static bool Execute(List <LogRecordModel> recordModelList, Guid fileGuid, KLog uploaderLog)
        {
            Dictionary <Guid, LogRecordModel> blockCache = new Dictionary <Guid, LogRecordModel>();

            foreach (var record in recordModelList)
            {
                if (record.LogData.Contains("KLOG_BLOCK"))
                {
                    if (record.LogData.Contains("KLOG_BLOCK_START"))
                    {
                        blockCache.Add(record.BlockID, record);
                    }
                    else if (record.LogData.Contains("KLOG_BLOCK_STOP"))
                    {
                        var startBlock = blockCache[record.BlockID];

                        if (startBlock != null)
                        {
                            var checkAddBlockResponse = DataAccessor.AddBlock(record, startBlock, instanceId: fileGuid);

                            if (!checkAddBlockResponse.Success)
                            {
                                uploaderLog.Error($"SQL Expection on [UploadAllLogs].[AddBlock] - Message: {checkAddBlockResponse.Message}");
                                return(false);
                            }
                        }
                        else
                        {
                            uploaderLog.Error($"Starting Block not found, is missing from Block pair.");
                        }

                        blockCache.Remove(record.BlockID);
                    }
                    else
                    {
                        uploaderLog.Error($"Malformed Block");
                    }
                }
                else
                {
                    if (record.LogType == "Metric")
                    {
                        var jsonString = record.LogData.Replace("#", "\"");
                        var metric     = JsonConvert.DeserializeObject <MetricRecordModel>(jsonString);

                        var checkMetricResponse = DataAccessor.AddMetric(record, metric, instanceId: fileGuid);

                        if (!checkMetricResponse.Success)
                        {
                            uploaderLog.Error($"SQL Expection on [UploadAllLogs].[AddMetric] - Message: {checkMetricResponse.Message}");
                            return(false);
                        }
                    }
                    else if (record.LogType == "Result")
                    {
                        var jsonString = record.LogData.Replace("#", "\"");
                        var result     = JsonConvert.DeserializeObject <ResultRecordModel>(jsonString);

                        var checkResultResponse = DataAccessor.AddResult(record, result, instanceId: fileGuid);

                        if (!checkResultResponse.Success)
                        {
                            uploaderLog.Error($"SQL Expection on [UploadAllLogs].[AddResult] - Message: {checkResultResponse.Message}");
                            return(false);
                        }
                    }
                    else
                    {
                        if (record.LogData.Length > Configuration.MessageLength)
                        {
                            var messageCap   = Configuration.MessageLength - 20;
                            var cleanLogData = "[ERROR-MAX-" + Configuration.MessageLength + "]";
                            cleanLogData  += record.LogData.Substring(1, messageCap);
                            record.LogData = cleanLogData;
                        }

                        var checkAddInstanceStop = DataAccessor.AddLog(record, instanceId: fileGuid);

                        if (!checkAddInstanceStop.Success)
                        {
                            uploaderLog.Error($"SQL Expection on [UploadAllLogs].[AddLog] - Message: {checkAddInstanceStop.Message}");
                            return(false);
                        }
                    }
                }
            }

            return(true);
        }
예제 #17
0
        /// <summary>
        /// Send "KLOG_S_$(guid).txt" files to Azure Storage Blob. On success, local file is renamed to "KLOG_A_$(guid).txt" to set as archive.
        /// </summary>
        /// <param name="sendFiles"></param>
        /// <param name="containerName"></param>
        public static void Execute()
        {
            using (KLog logSend = new KLog("ClassSendLogs-MethodExecute"))
            {
                try
                {
                    if (Capsule.SendFileCount() > 0)
                    {
                        logSend.Info($" File Count => {Capsule.SendFileCount().ToString()}");

                        foreach (var sendFile in Capsule.SendFiles)
                        {
                            // Parse connection string
                            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(Configuration.AzureStorage);

                            // Create the blob client
                            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

                            // Retrieve container reference -- create if it's not availble
                            CloudBlobContainer container = blobClient.GetContainerReference(Configuration.AzureContainer);
                            container.CreateIfNotExistsAsync().Wait();

                            // Build KLOG _R_ead file name to use on the blob write
                            var blobfileName = @"\KLOG_R_" + sendFile.FileGuid.ToString() + ".txt";

                            // Retrieve blob reference -- example: containerName\$(localDir)\KLOG_R_$(guid).txt
                            CloudBlockBlob blockBlob = container.GetBlockBlobReference(sendFile.DirName + blobfileName);

                            // Check if the file already exist before trying to send
                            if (!blockBlob.ExistsAsync().GetAwaiter().GetResult())
                            {
                                // Create or overwrite the "myblob" blob with contents from a local file
                                using (var fileStream = System.IO.File.OpenRead(sendFile.FullPath))
                                {
                                    blockBlob.UploadFromStreamAsync(fileStream).GetAwaiter().GetResult();
                                    logSend.Info($"Send Status => Sending: {blockBlob.Name}");
                                }

                                // Check and then Rename local file after file has been sent to Azure Storage Blob
                                if ((container.GetBlockBlobReference(sendFile.DirName + blobfileName)).ExistsAsync().GetAwaiter().GetResult())
                                {
                                    logSend.Info("Send Status => |- Transmission Confirmed.");

                                    var renamefileName = sendFile.Path + @"\KLOG_A_" + sendFile.FileGuid.ToString() + ".txt";

                                    logSend.Info($"Send Status => |- Renaming: {renamefileName}");

                                    File.Move(sendFile.FullPath, renamefileName);
                                }
                            }

                            // Files already exist in Azure Storage Blob -- rename local file for archiving
                            else
                            {
                                logSend.Info($"Send Status => Exist. Skip Sending File: {sendFile.FileName}");

                                var renamefileName = sendFile.Path + @"\KLOG_A_" + sendFile.FileGuid.ToString() + ".txt";

                                logSend.Info($"Send Status => |- Renaming: {renamefileName}");

                                File.Move(sendFile.FullPath, renamefileName);
                            }
                        }
                    }
                    else
                    {
                        logSend.Info("No files were sent.");
                    }
                }
                catch (Exception ex)
                {
                    logSend.Error($"{ex.ToString()}");
                }
            }
        }
예제 #18
0
        /// <summary>
        /// Collect and tag all local "KLOG_$(tag)_$(guid).txt" files from provided filepath.
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns>List of FileModel type</returns>
        public static List <FileModel> Execute(string filePath)
        {
            List <FileModel> fileMetadata = new List <FileModel>();

            using (KLog log = new KLog("ClassCollectLogs-MethodExecute"))
            {
                try
                {
                    // Search for all folders in the provide root filePath -- if you're using KLOG for more than one service locally, divide them by folders here
                    var directories = Directory.GetDirectories(filePath);

                    foreach (var d in directories)
                    {
                        // Logging
                        DirectoryInfo dInfo = new DirectoryInfo(d);
                        log.Info($"DirectoryInfo => Full Directory: {d}");
                        log.Info($"DirectoryInfo => Directory Name: {dInfo.Name}");

                        // Scan each folder for KLOG's
                        foreach (var file in dInfo.GetFiles("*.txt"))
                        {
                            FileModel fileModel = new FileModel();

                            // if KLOG
                            if (file.Name.Count() == 47 && file.Name.Contains("KLOG_"))
                            {
                                // Load metadata
                                fileModel.FullPath = file.FullName;
                                fileModel.Path     = file.DirectoryName;
                                fileModel.FileName = file.Name;
                                fileModel.TagCode  = -1;
                                fileModel.FileDate = file.LastWriteTimeUtc;
                                fileModel.DirName  = dInfo.Name;

                                // Parse file name down to GUID and Tag
                                fileModel.FileGuid = Guid.Parse(file.Name.Substring(7, 36));

                                fileModel.Tag = file.Name.Substring(1, 6);

                                if (file.Name.Contains("KLOG_S"))
                                {
                                    fileModel.TagCode = 1;
                                }

                                if (file.Name.Contains("KLOG_W"))
                                {
                                    fileModel.TagCode = 2;
                                }

                                if (file.Name.Contains("KLOG_A"))
                                {
                                    fileModel.TagCode = 3;
                                }

                                // Logging
                                log.Info($"GetFileDetails => FullPath: {fileModel.FullPath}");
                                log.Info($"GetFileDetails => |- Tag: {fileModel.Tag}, Tag Code: {fileModel.TagCode}, File Date: {fileModel.FileDate}");

                                fileMetadata.Add(fileModel);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    log.Error($"{ex.ToString()}");
                }
            }

            return(fileMetadata);
        }
예제 #19
0
        static void Main(string[] args)
        {
            Console.WriteLine("Testing Static Kiroku Logger");

            KManager.Configure(Global.KirokuTagList);

            KManager.Open();

            using (KLog klog = new KLog("testing block one"))
            {
                klog.Trace("testing trace one");

                klog.Info("testing info one");

                klog.Warning("testing warning one");

                klog.Error("testing error one");

                klog.Metric("test one", 1);

                klog.Success("test one success");
            }

            KManager.Close();

            KManager.Configure(Global.KirokuTagList, dynamic: true);

            Console.WriteLine("\n\rTrying to use Static Logger while Dynamic=true Kiroku Logger");
            try
            {
                KManager.Open();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Open Exception: {ex.ToString()}");
            }

            try
            {
                KManager.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Close Exception: {ex.ToString()}");
            }

            Console.WriteLine("\n\rTesting Non-Nested Dynamic Kiroku Logger");
            using (KLog klog = new KLog("testing block two"))
            {
                klog.Trace("testing trace two");

                klog.Info("testing info two");

                klog.Warning("testing warning two");

                klog.Error("testing error two");

                klog.Metric("test two", 1);

                klog.Success("test two success");
            }

            Console.WriteLine("\n\rTesting Nested Dynamic Kiroku Logger");
            using (KLog klog = new KLog("testing block three"))
            {
                klog.Trace("testing trace three");

                klog.Info("testing info three");

                klog.Warning("testing warning three");

                klog.Error("testing error three");

                klog.Metric("test three", 1);

                klog.Success("test three success");

                using (KLog klog2 = new KLog("nested testing block three", klog))
                {
                    klog2.Trace("nested testing trace three");

                    klog2.Info("nested testing info three");

                    klog2.Warning("nested testing warning three");

                    klog2.Error("nested testing error three");

                    klog2.Metric("nested test three", 1);

                    klog2.Success("nested test three success");
                }
            }

            Console.WriteLine("\n\rTesting Task<Nested Dynamic> Kiroku Logger");

            //#region Dynamic-False

            //for (int instanceIteration = 1; instanceIteration <= Global.InstanceLoop; instanceIteration++)
            //{
            //    KManager.Online(Global.KirokuTagList);

            //    for (int blockIteration = 1; blockIteration <= Global.BlockLoop; blockIteration++)
            //    {
            //        using (KLog klog = new KLog($"Block-{instanceIteration}-{blockIteration}"))
            //        {
            //            klog.Metric("Test Metric One", blockIteration);
            //            klog.Metric("Test Metric Two", true);
            //            klog.Metric("Test Metric Three", 2.33);

            //            if (Global.TraceOn)
            //            {
            //                try
            //                {
            //                    // Trace
            //                    for (int traceMeter = 1; traceMeter <= Global.TraceLoopCount; traceMeter++)
            //                    {
            //                        klog.Trace(Generator.Execute(Global.TraceCharCount));
            //                    }

            //                    // Info
            //                    if (Global.InfoOn)
            //                    {
            //                        for (int infoMeter = 1; infoMeter <= Global.InfoLoopCount; infoMeter++)
            //                        {
            //                            klog.Info(Generator.Execute(Global.InfoCharCount));
            //                        }
            //                    }

            //                    // Warning
            //                    if (Global.WarningOn)
            //                    {
            //                        for (int warningMeter = 1; warningMeter <= Global.WarningLoopCount; warningMeter++)
            //                        {
            //                            klog.Warning(Generator.Execute(Global.WarningCharCount));
            //                        }
            //                    }

            //                    // Error
            //                    if (Global.ErrorOn)
            //                    {
            //                        for (int errorMeter = 1; errorMeter <= Global.ErrorLoopCount; errorMeter++)
            //                        {
            //                            klog.Error(Generator.Execute(Global.ErrorCharCount));
            //                        }
            //                    }

            //                    klog.Success();
            //                }
            //                catch (Exception e)
            //                {
            //                    klog.Error($"KFlow Exception: {e.ToString()}");
            //                    klog.Failure();
            //                }
            //            }
            //        }
            //    }

            //    KManager.Offline();
            //}

            //#endregion

            var items       = new string[] { "Task1", "Task2", "Task3", "Task4" };
            var tasks       = new Task[items.Length];
            var taskCounter = 0;

            foreach (var item in items)
            {
                tasks[taskCounter] = new Task(() => DynamicLog(item));

                taskCounter++;
            }

            Parallel.ForEach(tasks, (t) => { t.Start(); });
            Task.WaitAll(tasks);

            Console.ReadKey();
        }