public void Common_Create_New_File_On_Size_Limit_Exceed() { TextFileLogger logger = new TextFileLogger("log", 10000); for (int i = 0; i < 200; i++) { logger.Log(String.Format("{0}, Запись в журнале", DateTime.Now)); } Assert.IsTrue(File.Exists("log-0.log")); FileInfo fileInfo = new FileInfo("log-0.log"); Assert.IsTrue(fileInfo.Length > 10000); Assert.IsTrue(File.Exists("log-1.log")); StreamReader streamReader = new StreamReader(new FileStream("log-1.log", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)); Assert.IsTrue(streamReader.ReadLine().Contains("Запись в журнале")); streamReader.Close(); streamReader.Dispose(); logger.Dispose(); }
public void CreateProvider() { if (File.Exists(LogFilePath)) File.Delete(LogFilePath); logger = new TextFileLogger(); }
public void BeginScopeIsNotImplemented() { var mockFileSystem = new MockFileSystem(); var logger = new TextFileLogger(LogLevel.Information, _filePath, mockFileSystem); Assert.Throws <NotImplementedException>(() => logger.BeginScope("tester")); }
/// <summary> /// This method runs the DI Example. /// </summary> private void DependencyInject() { var logger = new TextFileLogger(); var di = new Worker(logger); di.DoSomeWork(logger); }
public static string GetEmailContentToXmlByNode(string fileName, string node) { TextFileLogger log = new TextFileLogger(); try { XmlDocument oXmlDoc = new XmlDocument(); // oXmlDoc.Load(SF.Framework.SFConfig.WebsitePhysicalPath + "/Content/EmailTemplate/" + fileName); //AppDomain.CurrentDomain.BaseDirectory string path = ""; if (System.Web.HttpContext.Current != null) { path = System.Web.HttpContext.Current.Server.MapPath("~/Content/EmailTemplate/" + fileName); } else { path = ConfigurationManager.AppSettings["WebsitePath"] + "/Content/EmailTemplate/" + fileName; } oXmlDoc.Load(path); XmlNode oNode = oXmlDoc.SelectSingleNode("/emails/email[position()=1]"); string body = oNode.SelectSingleNode(node).InnerText; return(body); } catch (Exception ex) { log.Log(ex); return(""); } }
private List <string> LoadSubdomains(string url) { string testUrl = url.Trim(new char[] { '*', '.' }); var subDomains = new List <string>(); //This will have to get moved to a central db List <string> knownSubdomains = new List <string>(); string existingFile = Path.Combine(Settings.ExistingDir, testUrl.Replace(".", "") + ".txt"); if (File.Exists(existingFile)) { knownSubdomains = File.ReadAllLines(existingFile).ToList(); } HunterRequest request = new HunterRequest(); request.Domain = testUrl; request.KnownSubdomains = knownSubdomains; request.SecurityTrailsAPIKey = Settings.SecurityTrailsAPI; request.VirusTotalAPIKey = Settings.VirusTotalAPI; subDomains = Hunter.GatherAll(request); Log("Subdomains found: " + subDomains.Count); TextFileLogger.WriteOverwriteFile(Settings.ExistingDir, testUrl.Replace(".", "") + ".txt", subDomains); return(subDomains); }
private static void ExportData <T>(bool confirmExport) { if (!confirmExport) { return; } string prefix = typeof(T).Name; ILogger logger = new TextFileLogger(prefix, 10000000, true); if (prefix == "Bar") { logger.Log("<TICKER>,<PER>,<DATE>,<TIME>,<OPEN>,<HIGH>,<LOW>,<CLOSE>,<VOL>"); foreach (Bar item in TradingData.Instance.Get <IEnumerable <Bar> >().OrderBy(i => i.DateTime)) { logger.Log(item.ToFinamString()); } } else { foreach (T item in TradingData.Instance.Get <IEnumerable <T> >()) { logger.Log(item.ToString()); } } }
static void Main(string[] args) { /////////////////////////////////////////////// //Local Variables string path = Environment.CurrentDirectory; string fileName = "ExceptionLog.txt"; int inputLength = 4; int maxGuesses = 10; List <int> validNumbers = new List <int> { 1, 2, 3, 4, 5, 6 }; Game game; TextFileLogger logger; /////////////////////////////////////////////// logger = new TextFileLogger(path, fileName); game = new Game(logger); game.InitializeGame(inputLength, maxGuesses, validNumbers); game.StartGameLoop(); Console.Write("\n\nPress any key to close the console. Thank you for playing! :)"); Console.ReadKey(true); }
public void WriteLogFileTest() { String lCompareTextFromFile; String lCompareText; String lDate = System.DateTime.Today.Year.ToString() + System.DateTime.Today.Month.ToString() + System.DateTime.Today.Day.ToString(); String lFile = "TextFileLoggerTest-" + lDate; String lMethod = "WriteLogFileTest"; String lMessage = ""; String lTime = System.DateTime.Now.ToString(); lMessage = "Datos para grabar."; lMessage += "\r\n" + "Segunda linea con datos."; lMessage += "\r\n" + "Tercera linea con datos."; //lMessage += "\n" + ""; TextFileLogger lTextFileLogger = new TextFileLogger(); lCompareText = ((((lTime + " - ") + lFile + " - ") + lMethod + " - ") + lMessage + "\r\n"); lCompareText += "\n"; lCompareText += "---------------------------------------- \n"; lTextFileLogger.WriteLogFile(lFile, lMethod, lMessage, lTime); lCompareTextFromFile = lTextFileLogger.ReadLogFile(); Assert.AreEqual(lCompareText, lCompareTextFromFile); }
public void TextFileLoggerCanLog() { string msgText = "text file logger test"; string expected = String.Empty; string actual = String.Empty; Message msg = new GeneralMessage(msgText); StubFileFactory fileFactory = new StubFileFactory("dummy.txt"); TextFileLogger txtlogger = new TextFileLogger(fileFactory); using (MemoryStream ms = fileFactory.MemoryStream) { txtlogger.Log(msg); ms.Position = 0; using (StreamReader reader = new StreamReader(ms, Encoding.UTF8)) { actual = reader.ReadToEnd(); } } expected = DateTime.Now.ToShortDateString() + " " + msgText + Environment.NewLine; Assert.AreEqual(expected, actual); }
static void Main() { //------------------------- // 2번 실행 안 되도록 string strExe = "KMC_S2_CHT.exe"; if (!AUtil.IsAppFirstRun(strExe)) { MessageBox.Show("Program(" + strExe + ") is running!", "Program execution", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } //------------------------- // 2016.06.18 // license check AVisionProBuild.CheckLicense("VisionPro.PatMax"); ExceptionLogger logger = new ExceptionLogger(); TextFileLogger txtLogger = new TextFileLogger(); logger.AddLogger(txtLogger); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FrmMain()); }
protected override void OnStartup(StartupEventArgs e) { try { var config = ApplicationConfiguration.FromJsonFile(_configFilename); IEyeTracker eyeTracker = null; switch (config.EyeTrackerName.ToUpper()) { case "TOBII4C": eyeTracker = new TobiiEyeTracker4C(); break; default: throw new NotImplementedException($"Eye tracker {config.EyeTrackerName} not supported"); } var logger = new TextFileLogger(); App.Current.DispatcherUnhandledException += (sender, ev) => { #if DEBUG ev.Handled = true; #endif logger.Log(ev.Exception); }; var overlays = new List <IOverlay>(); overlays.Add(new PositionOverlay()); var window = new MainWindow(config, eyeTracker, logger, overlays); window.Show(); } catch (Exception exception) { throw new StartupException("Initialization error", exception); } }
private void LogLinks(string log) { if (String.IsNullOrEmpty(log)) { return; } TextFileLogger.Log(Settings.InterstingURLs, DateTime.Now.ToString("yyyy-MM-dd") + ".txt", log); }
public static void Main(string[] args) { var logger = new TextFileLogger("log.txt"); var renamerArguments = GetArguments(args, logger); ProcessExecutor processExecutor = new ProcessExecutor(); processExecutor.Execute(renamerArguments, logger); }
public void TextFileCanBeCreated() { IFileFactory fileFactory = new StubFileFactory("dummy.txt"); TextFileLogger txtLogger = new TextFileLogger(fileFactory); Assert.IsNotNull(txtLogger); Assert.IsInstanceOfType(txtLogger, typeof(ILogger)); }
public void CreateProvider() { if (File.Exists(LogFilePath)) { File.Delete(LogFilePath); } logger = new TextFileLogger(); }
public static void ExportData <T>(string prefix, IEnumerable <T> data) { //string prefix = typeof(T).Name; ILogger logger = new TextFileLogger(prefix, 10000000, true); foreach (T item in data) { logger.Log(item.ToString()); } }
private void Application_Startup(object sender, StartupEventArgs e) { var assemblyInfo = new AssemblyInfo(typeof(App).Assembly, "Resources.LICENSE"); var dataDirectory = new AppDataRoaming(assemblyInfo.Product); var logger = new TextFileLogger(dataDirectory.GetFilePath($"{assemblyInfo.FileName}.log")); AppHelper.AssemblyInfo = assemblyInfo; AppHelper.DataDirectory = dataDirectory; AppHelper.Logger = logger; AppHelper.CatchUnhandledException = true; AppHelper.SetAppMutex($"Global\\{assemblyInfo.Guid}"); }
public Task Execute(IJobExecutionContext context) { var logger = new TextFileLogger(); var policyConfig = new PolicyConfig(); ITaskHandler taskHandler = new PolicyTaskHandler(logger, policyConfig); taskHandler.Process(); //logger.Log(LogLevel.Debug, "测试"); return(Task.CompletedTask); }
public MerakiModule(TextFileLogger logger, SmartFlowContext context) : base("/meraki") { // Meraki will use this to validate we are the correct host Get["/"] = _ => Settings.Default.Validator; Post["/"] = _ => { var req = this.Bind<MerakiDto>(); // secret didnt match, return FORBIDDEN if (req.Secret != Settings.Default.Secret) return 403; // log to file (will log to database once its all working etc..) logger.Write(req.ToString(), Enums.LogLevel.Information); var floors = req.Data.ApFloors.Select(x => x.ToFloorEntity(req.Data.ApMac)); foreach (var floor in floors) { if (context.Floors.Any(x => x.ApMac == floor.ApMac && x.Name == floor.Name)) { context.Floors.Attach(floor); } else { context.Floors.Add(floor); } } var thisTime = DateTime.Now; var isDaylight = TimeZoneInfo.Local.IsDaylightSavingTime(thisTime); var observations = req.Data.Observations.Select(y => new Observation { ApMac = req.Data.ApMac, ClientMac = y.ClientMac, Ipv4 = y.Ipv4, Ipv6 = y.Ipv6, Manufacturer = y.Manufacturer, Os = y.Os, Rssi = y.Rssi, SeenTime = isDaylight ? y.SeenTime.AddHours(1) : y.SeenTime, SeenEpoch = y.SeenEpoch, Location = y.Location != null ? y.Location.ToLocationEntity(req.Data) : null }); context.Observations.AddRange(observations); // return CREATED return 201; }; }
public SelfContainedMigrator(string migrationName, Guid migrationId, string sourceName, string targetName) { JobQueueManager.Start(1); _integration = new Integration(migrationId, migrationName, Assembly.GetCallingAssembly().Location, sourceName, targetName); var loggingPath = Path.GetDirectoryName(Assembly.GetCallingAssembly().Location) + @"\Logs"; var textFileLogger = new TextFileLogger(loggingPath); SyncEngineLogger.RegisterLogger(textFileLogger, LoggingLevel.ErrorsWarningsInfoDebugAndTrace, -1); }
public void Instance_Get2Instances_ReturnsSameInstances() { TextFileLogger.CreateInstance("test"); var instance1 = TextFileLogger.GetInstance(); var instance2 = TextFileLogger.GetInstance(); Assert.AreSame(instance1, instance2); instance1.TestField++; Assert.AreEqual(instance1.TestField, instance2.TestField); instance2.TestField++; Assert.AreEqual(instance1.TestField, instance2.TestField); }
public void RunProcessAndLogToTextFile() { TextFileLogger textFileLogger = new TextFileLogger(); try { //Run process } catch (Exception ex) { textFileLogger.LogMessage(ex.Message); } }
protected override void ConfigureApplicationContainer(TinyIoCContainer container) { base.ConfigureApplicationContainer(container); var logger = new TextFileLogger(Settings.Default.FilePath, "Request", null, 30, "SmartFlow", "1") { MaximumLogSize = 15 }; container.Register(logger); container.Register<JsonSerializer, SmartFlowJsonSerializer>(); logger.Write("Logging Configured", Enums.LogLevel.Information); }
public int SaveChanges() { try { int i = this.CurrentDbContext.SaveChanges(); return(i); } catch (Exception dbEx) { TextFileLogger log = new TextFileLogger(); log.Log(dbEx); return(0); } }
public static ILogger GetMultiTargetLogger(ILogger logger) { if (multiTargetLogger == null) { MultiTargetLogger multiLogger = new MultiTargetLogger(); TextFileLogger fileLogger = new TextFileLogger(); fileLogger.Folder = new DirectoryInfo(ContentRoot); multiLogger.AddLogger(fileLogger); multiLogger.AddLogger(logger); multiLogger.StartLoggingThread(); multiTargetLogger = multiLogger; } return(multiTargetLogger); }
public override void Load() { var loggers = new List <ILogger>(); var consoleLogger = new ConsoleLogger(); var decoratedConsoleLogger = new PrependDateLogger(consoleLogger); var fileLogger = new TextFileLogger(); var decoratedFileLogger = new PrependDateLogger(fileLogger); loggers.Add(consoleLogger); loggers.Add(decoratedConsoleLogger); loggers.Add(fileLogger); loggers.Add(decoratedFileLogger); this.Bind <ILogger>().To <CompositeLogger>().WithConstructorArgument(loggers); }
static public void HandleException(System.Exception ex, string message = "An errror occured in LBF Video Lib", bool ignoreException = true) { // Format the exception message. ExceptionFormatter formater = new ExceptionFormatter(); string formatedException = formater.Format(message, ex); // Log error message in production category. // If severity is critical then it also send error to config mail address. TextFileLogger.Log(formatedException, ErrorLogFileName); if (!ignoreException) { throw ex; } }
public void TraceLogWritesToTextFile(LogLevel logLevel) { var mockFileSystem = new MockFileSystem(); var logger = new TextFileLogger(LogLevel.Trace, _filePath, mockFileSystem); logger.Log(logLevel, _logMessage); var logFile = mockFileSystem.GetFile(_filePath); var fileContents = logFile.TextContents.ToLower(); Assert.IsTrue(logLevel == LogLevel.None ? fileContents.Contains($"{_logMessage}") : fileContents.Contains($"{logLevel.ToString().ToLower()}: {_logMessage}")); }
public void DeleteFileWhenInitialize() { "使用 With 初始化时,不能要求文件存在。".Test((Func <TextFileLogger, TextFileLogger> extraBuilder) => { var testFile = PrepareNotExistFile("test21.md"); var aLogger = extraBuilder(new TextFileLogger(new FileInfo(testFile.FullName))); aLogger.Message("YY"); aLogger.Close(); // 无异常。 }).WithArguments( x => x.WithMaxFileSize(100), x => x.WithMaxLineCount(100), x => x.WithMaxLineCount(100, 50), x => x.WithWholeFileOverride() ); "初始化时,超过大小的文件内容会清空。".Test(() => { const string testFile = "test22.md"; File.WriteAllText(testFile, "XXXXXXXX\n"); var aLogger = new TextFileLogger(new FileInfo(testFile)) .WithMaxFileSize(4); aLogger.Message("YY"); aLogger.Close(); var lines = File.ReadAllLines(testFile); Assert.AreEqual(1, lines.Length); Assert.IsTrue(lines[0].Contains("YY")); }); "初始化时,超过行数的文件前面行会删除。".Test(() => { const string testFile = "test23.md"; File.WriteAllText(testFile, "XXXXXXXX\n\nYYYYYYYY\nZZZZZZZZ\n"); var aLogger = new TextFileLogger(new FileInfo(testFile)) .WithMaxLineCount(3, 1); aLogger.Message("WW"); aLogger.Close(); var lines = File.ReadAllLines(testFile); Assert.AreEqual(2, lines.Length); Assert.IsTrue(lines[0].Contains("ZZZZZZZZ")); }); }
public void SubscribeShouldIncrementSubscribers() { BamServer server = CreateServer(MethodBase.GetCurrentMethod().Name); ILogger logger = new TextFileLogger(); Expect.AreEqual(0, server.Subscribers.Length); server.Subscribe(logger); Expect.AreEqual(1, server.Subscribers.Length); server.Subscribe(logger); Expect.AreEqual(1, server.Subscribers.Length); // should only get added once ILogger winLogger = new WindowsLogger(); server.Subscribe(winLogger); Expect.AreEqual(2, server.Subscribers.Length); Expect.IsTrue(server.IsSubscribed(winLogger)); }
private static void ExportData <T>(bool confirmExport) { if (!confirmExport) { return; } string prefix = typeof(T).Name; ILogger logger = new TextFileLogger(prefix, 10000000); foreach (T item in TradingData.Instance.Get <IEnumerable <T> >()) { logger.Log(item.ToString()); } }
static void Main(string[] args) { ProcessLog = new TextFileLogger(Settings.Default.LogPath, AssemblyName, null, Settings.Default.LogDeleteThreshold, Title, Version.ToString()) { MaximumLogSize = Settings.Default.LogFileMaxSize }; #if DEBUG var service = new HostService(); service.Start(); Console.WriteLine("Service Running..."); Console.ReadLine(); #else RunService(); #endif }
private void unlockFilesButton_Click(object sender, EventArgs e) { ToggleAllButtons(false); var confirmation = MessageBox.Show("Ready to start craXcel?", "Confirm", MessageBoxButtons.YesNo); if (confirmation == DialogResult.No || fileListBox.Items.Count == 0) { ToggleAllButtons(true); return; } List <string> filePaths = fileListBox.Items.OfType <string>().ToList(); var logger = new TextFileLogger(); int filesUnlocked = CraxcelProcessor.UnlockFiles(filePaths, logger); MessageBox.Show($"{filesUnlocked}/{filePaths.Count} files unlocked.", "Complete"); // TO-DO - Possibly only works on Windows? try { var craxcelDir = new ProcessStartInfo(ApplicationSettings.CRAXCEL_DIR.FullName) { UseShellExecute = true, Verb = "open" }; var logFile = new ProcessStartInfo(logger.LogFile.FullName) { UseShellExecute = true, Verb = "open" }; Process.Start(craxcelDir); Process.Start(logFile); } catch { } ResetForm(); ToggleAllButtons(true); }