public static void FlushTests() { var factory = new LogFactory(); factory.Flush(); factory.Flush(100); factory.Flush(TimeSpan.FromSeconds(1)); }
public static void EnableDisableLogging() { var factory = new LogFactory(); factory.DisableLogging(); factory.EnableLogging(); factory.IsLoggingEnabled(); }
public SessionFactory(Application app, MessageStoreFactory storeFactory, LogFactory logFactory, IMessageFactory messageFactory) { application_ = app; messageStoreFactory_ = storeFactory; logFactory_ = logFactory; messageFactory_ = messageFactory ?? new DefaultMessageFactory(); }
public SocketInitiator(Application application, MessageStoreFactory storeFactory, SessionSettings settings, LogFactory logFactory) : base(application, storeFactory, settings, logFactory) { app_ = application; storeFactory_ = storeFactory; settings_ = settings; logFactory_ = logFactory; }
public void Configuration_PrivateBinPathIsNull_DoesNotThrowWhen() { AppDomainHelper.PrivateBinPath = () => null; var fakeFileSystem = A.Fake<IFileSystem>(); var factory = new LogFactory(fakeFileSystem); var loggingConfiguration = factory.Configuration; }
public void GenericGetCurrentClassLoggerTest() { LogFactory<MyLogger> lf = new LogFactory<MyLogger>(); MyLogger l1 = lf.GetCurrentClassLogger(); MyLogger l2 = lf.GetCurrentClassLogger(); Assert.Same(l1, l2); Assert.Equal("NLog.UnitTests.GetLoggerTests", l1.Name); }
public void Configuration_PrivateBinPathIsNull_DoesNotThrow() { var fakeAppDomain = A.Fake<IAppDomain>(); A.CallTo(() => fakeAppDomain.PrivateBinPath).Returns(null); LogFactory.CurrentAppDomain = fakeAppDomain; var fakeFileSystem = A.Fake<IFileSystem>(); var factory = new LogFactory(fakeFileSystem); var dummy = factory.Configuration; }
public void Configuration_WithPrivateBinPath_CheckIfConfigFileExistsInPrivateBinPath() { const string AnyDirectory = "C:\\any\\"; AppDomainHelper.PrivateBinPath = () => AnyDirectory; var fakeFileSystem = A.Fake<IFileSystem>(); var factory = new LogFactory(fakeFileSystem); var loggingConfiguration = factory.Configuration; A.CallTo(() => fakeFileSystem.File.Exists(Path.Combine(AnyDirectory, "NLog.config"))).MustHaveHappened(); }
public Session( Application app, MessageStoreFactory storeFactory, SessionID sessID, DataDictionaryProvider dataDictProvider, SessionSchedule sessionSchedule, int heartBtInt, LogFactory logFactory, IMessageFactory msgFactory, string senderDefaultApplVerID) { this.Application = app; this.SessionID = sessID; this.DataDictionaryProvider = new DataDictionaryProvider(dataDictProvider); this.schedule_ = sessionSchedule; this.msgFactory_ = msgFactory; this.SenderDefaultApplVerID = senderDefaultApplVerID; this.SessionDataDictionary = this.DataDictionaryProvider.GetSessionDataDictionary(this.SessionID.BeginString); if (this.SessionID.IsFIXT) this.ApplicationDataDictionary = this.DataDictionaryProvider.GetApplicationDataDictionary(this.SenderDefaultApplVerID); else this.ApplicationDataDictionary = this.SessionDataDictionary; Log log; if (null != logFactory) log = logFactory.Create(sessID); else log = new NullLog(); state_ = new SessionState(log, heartBtInt) { MessageStore = storeFactory.Create(sessID) }; this.PersistMessages = true; this.ResetOnDisconnect = false; this.SendRedundantResendRequests = false; this.ValidateLengthAndChecksum = true; this.CheckCompID = true; this.MillisecondsInTimeStamp = true; this.EnableLastMsgSeqNumProcessed = false; this.MaxMessagesInResendRequest = 0; this.SendLogoutBeforeTimeoutDisconnect = false; this.IgnorePossDupResendRequests = false; if (!IsSessionTime) Reset("Out of SessionTime at construction"); else if (IsNewSession) Reset("New session"); lock (sessions_) { sessions_[this.SessionID] = this; } this.Application.OnCreate(this.SessionID); this.Log.OnEvent("Created session"); }
public void EnableAndDisableLogging() { LogFactory factory = new LogFactory(); #pragma warning disable 618 // In order Suspend => Resume Assert.True(factory.IsLoggingEnabled()); factory.DisableLogging(); Assert.False(factory.IsLoggingEnabled()); factory.EnableLogging(); Assert.True(factory.IsLoggingEnabled()); #pragma warning restore 618 }
public void Configuration_WithPrivateBinPath_CheckIfConfigFileExistsInPrivateBinPath() { const string AnyDirectory = "C:\\any\\"; var fakeAppDomain = A.Fake<IAppDomain>(); A.CallTo(() => fakeAppDomain.PrivateBinPath).Returns(new[] { AnyDirectory }); LogFactory.CurrentAppDomain = fakeAppDomain; var fakeFileSystem = A.Fake<IFileSystem>(); var factory = new LogFactory(fakeFileSystem); var dummy = factory.Configuration; A.CallTo(() => fakeFileSystem.File.Exists(Path.Combine(AnyDirectory, "NLog.config"))).MustHaveHappened(); }
public void GenericGetLoggerTest() { LogFactory<MyLogger> lf = new LogFactory<MyLogger>(); MyLogger l1 = lf.GetLogger("AAA"); MyLogger l2 = lf.GetLogger("AAA"); MyLogger l3 = lf.GetLogger("BBB"); Assert.Same(l1, l2); Assert.NotSame(l1, l3); Assert.Equal("AAA", l1.Name); Assert.Equal("BBB", l3.Name); }
internal static void Write(Type loggerType, TargetWithFilterChain targets, LogEventInfo logEvent, LogFactory factory) { if (targets == null) { return; } #if !NET_CF StackTraceUsage stu = targets.GetStackTraceUsage(); if (stu != StackTraceUsage.None && !logEvent.HasStackTrace) { StackTrace stackTrace; #if !SILVERLIGHT stackTrace = new StackTrace(StackTraceSkipMethods, stu == StackTraceUsage.WithSource); #else stackTrace = new StackTrace(); #endif int firstUserFrame = FindCallingMethodOnStackTrace(stackTrace, loggerType); logEvent.SetStackTrace(stackTrace, firstUserFrame); } #endif int originalThreadId = Thread.CurrentThread.ManagedThreadId; AsyncContinuation exceptionHandler = ex => { if (ex != null) { if (factory.ThrowExceptions && Thread.CurrentThread.ManagedThreadId == originalThreadId) { throw new NLogRuntimeException("Exception occurred in NLog", ex); } } }; for (var t = targets; t != null; t = t.NextInChain) { if (!WriteToTargetWithFilterChain(t, logEvent, exceptionHandler)) { break; } } }
/// FIXME public Session( Application app, MessageStoreFactory storeFactory, SessionID sessID, DataDictionaryProvider dataDictProvider, SessionSchedule sessionSchedule, int heartBtInt, LogFactory logFactory, IMessageFactory msgFactory) { this.Application = app; this.SessionID = sessID; this.DataDictionaryProvider = new DataDictionaryProvider(dataDictProvider); this.schedule_ = sessionSchedule; this.msgFactory_ = msgFactory; this.SessionDataDictionary = this.DataDictionaryProvider.GetSessionDataDictionary(this.SessionID.BeginString); if (this.SessionID.IsFIXT) this.ApplicationDataDictionary = this.DataDictionaryProvider.GetApplicationDataDictionary(this.SenderDefaultApplVerID); else this.ApplicationDataDictionary = this.SessionDataDictionary; Log log; if (null != logFactory) log = logFactory.Create(sessID); else log = new NullLog(); state_ = new SessionState(log, heartBtInt); state_.MessageStore = storeFactory.Create(sessID); this.PersistMessages = true; this.ResetOnDisconnect = false; this.SendRedundantResendRequests = false; this.ValidateLengthAndChecksum = true; this.CheckCompID = true; if (!CheckSessionTime()) Reset(); lock (sessions_) { sessions_[this.SessionID] = this; } this.Application.OnCreate(this.SessionID); this.Log.OnEvent("Created session"); }
public void TypedGetLoggerTest() { LogFactory lf = new LogFactory(); MyLogger l1 = (MyLogger)lf.GetLogger("AAA", typeof(MyLogger)); MyLogger l2 = (MyLogger)lf.GetLogger("AAA", typeof(MyLogger)); Logger l3 = lf.GetLogger("AAA", typeof(Logger)); Logger l4 = lf.GetLogger("AAA", typeof(Logger)); Logger l5 = lf.GetLogger("AAA"); Logger l6 = lf.GetLogger("AAA"); Assert.AreSame(l1, l2); Assert.AreSame(l3, l4); Assert.AreSame(l5, l6); Assert.AreSame(l3, l5); Assert.AreNotSame(l1, l3); Assert.AreEqual("AAA", l1.Name); Assert.AreEqual("AAA", l3.Name); }
public void TypedGetCurrentClassLoggerTest() { LogFactory lf = new LogFactory(); MyLogger l1 = (MyLogger)lf.GetCurrentClassLogger(typeof(MyLogger)); MyLogger l2 = (MyLogger)lf.GetCurrentClassLogger(typeof(MyLogger)); Logger l3 = lf.GetCurrentClassLogger(typeof(Logger)); Logger l4 = lf.GetCurrentClassLogger(typeof(Logger)); Logger l5 = lf.GetCurrentClassLogger(); Logger l6 = lf.GetCurrentClassLogger(); Assert.AreSame(l1, l2); Assert.AreSame(l3, l4); Assert.AreSame(l5, l6); Assert.AreSame(l3, l5); Assert.AreNotSame(l1, l3); Assert.AreEqual("NLog.UnitTests.GetLoggerTests", l1.Name); Assert.AreEqual("NLog.UnitTests.GetLoggerTests", l3.Name); }
public AbstractInitiator(Application app, MessageStoreFactory storeFactory, SessionSettings settings, LogFactory logFactory, IMessageFactory messageFactory) { settings_ = settings; HashSet<SessionID> definedSessions = settings.GetSessions(); if (0 == definedSessions.Count) throw new ConfigError("No sessions defined"); SessionFactory factory = new SessionFactory(app, storeFactory, logFactory, messageFactory); foreach (SessionID sessionID in definedSessions) { Dictionary dict = settings.Get(sessionID); if ("initiator".Equals(dict.GetString(SessionSettings.CONNECTION_TYPE))) { sessionIDs_.Add(sessionID); sessions_[sessionID] = factory.Create(sessionID, dict); SetDisconnected(sessionID); } } if (0 == sessions_.Count) throw new ConfigError("No sessions defined for initiator"); }
/// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="xmlContents">The XML contents.</param> /// <param name="fileName">Name of the XML file.</param> /// <param name="logFactory">The <see cref="LogFactory" /> to which to apply any applicable configuration values.</param> internal XmlLoggingConfiguration([NotNull] string xmlContents, [CanBeNull] string fileName, LogFactory logFactory) : base(logFactory) { using (var stringReader = new StringReader(xmlContents)) { using (XmlReader reader = XmlReader.Create(stringReader)) { Initialize(reader, fileName); } } }
/// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="element">The XML element.</param> /// <param name="fileName">Name of the XML file.</param> /// <param name="ignoreErrors">If set to <c>true</c> errors will be ignored during file processing.</param> internal XmlLoggingConfiguration(XmlElement element, string fileName, bool ignoreErrors) { logFactory = LogManager.LogFactory; using (var stringReader = new StringReader(element.OuterXml)) { XmlReader reader = XmlReader.Create(stringReader); this.Initialize(reader, fileName, ignoreErrors); } }
private static LoggingConfiguration CreateConfigWithMemoryTarget(out MemoryTarget memoryTarget, string levelMessage = "${level}|${message}", LogFactory logFactory = null) { var config = new LoggingConfiguration(logFactory); memoryTarget = new MemoryTarget { Layout = levelMessage }; config.AddRuleForAllLevels(memoryTarget); if (logFactory != null) { logFactory.Configuration = config; } return(config); }
public NLogLoggerProvider(LogFactory logFactory) { _logFactory = logFactory; }
public async Task LargeWritesAreTruncated() { ILogWriter writer = LogFactory.NewWriter(DefaultHost, "c1", this); ILogReader reader = LogFactory.NewReader(this); List <Guid> functionIds = new List <Guid>(); // Max table request size is 4mb. That gives roughly 40kb per row. string smallValue = new string('y', 100); string largeValue = new string('x', 100 * 1000); string truncatedPrefix = largeValue.Substring(0, 100); for (int i = 0; i < 90; i++) { var functionId = Guid.NewGuid(); functionIds.Add(functionId); var now = DateTime.UtcNow; var item = new FunctionInstanceLogItem { FunctionInstanceId = functionId, Arguments = new Dictionary <string, string> { { "p1", largeValue }, { "p2", smallValue }, { "p3", smallValue }, { "p4", smallValue }, { "p5", null }, { "p6", "" } }, StartTime = now, EndTime = now.AddSeconds(3), FunctionName = "tst2", LogOutput = largeValue, ErrorDetails = largeValue, TriggerReason = largeValue }; await writer.AddAsync(item); } // If we didn't truncate, then this would throw with a 413 "too large" exception. await writer.FlushAsync(); // If we got here without an exception, then we successfully truncated the rows. // If we got here without an exception, then we successfully truncated the rows. // Lookup and verify var instance = await reader.LookupFunctionInstanceAsync(functionIds[0]); Assert.True(instance.LogOutput.StartsWith(truncatedPrefix)); Assert.True(instance.ErrorDetails.StartsWith(truncatedPrefix)); Assert.True(instance.TriggerReason.StartsWith(truncatedPrefix)); Assert.Equal(6, instance.Arguments.Count); Assert.True(instance.Arguments["p1"].StartsWith(truncatedPrefix)); Assert.Equal(smallValue, instance.Arguments["p2"]); Assert.Equal(smallValue, instance.Arguments["p3"]); Assert.Equal(smallValue, instance.Arguments["p4"]); Assert.Equal(null, instance.Arguments["p5"]); Assert.Equal("", instance.Arguments["p6"]); }
public async Task TimeRangeAcrossEpochs() { // Make some very precise writes and verify we read exactly what we'd expect. ILogWriter writer = LogFactory.NewWriter(DefaultHost, "c1", this); ILogReader reader = LogFactory.NewReader(this); // Time that functios are called. DateTime[] times = new DateTime[] { // Epoch 37 new DateTime(2012, 3, 6, 10, 11, 20, DateTimeKind.Utc), new DateTime(2012, 3, 7, 10, 11, 20, DateTimeKind.Utc), // consecutive Epoch 38 new DateTime(2012, 4, 8, 10, 11, 20, DateTimeKind.Utc), // Skip to Epoch 41 new DateTime(2012, 7, 9, 10, 11, 20, DateTimeKind.Utc) }; var logs = Array.ConvertAll(times, time => new FunctionInstanceLogItem { FunctionInstanceId = Guid.NewGuid(), FunctionName = CommonFuncName1, StartTime = time, }); var tasks = Array.ConvertAll(logs, log => WriteAsync(writer, log)); await Task.WhenAll(tasks); await writer.FlushAsync(); // Test point lookups for individual function instances. foreach (var log in logs) { var entry = await reader.LookupFunctionInstanceAsync(log.FunctionInstanceId); Assert.NotNull(entry); Assert.Equal(log.FunctionInstanceId, entry.FunctionInstanceId); Assert.Equal(log.FunctionName, entry.FunctionName); Assert.Equal(log.StartTime, entry.StartTime); Assert.Equal(log.EndTime, entry.EndTime); } // Try various combinations. await Verify(reader, DateTime.MinValue, DateTime.MaxValue, logs[3], logs[2], logs[1], logs[0]); // Infinite range, includes all. // Various combinations of straddling an epoch boundary await Verify(reader, Before(times[1]), After(times[2]), logs[2], logs[1]); await Verify(reader, Before(times[1]), Before(times[2]), logs[1]); await Verify(reader, After(times[1]), Before(times[2])); // Skipping over an empty epoch await Verify(reader, Before(times[1]), Before(times[3]), logs[2], logs[1]); // Now... delete the middle table; and verify the other data is still there. ILogTableProvider provider = this; var table = provider.GetTable("201204"); Assert.True(table.Exists()); table.Delete(); await Verify(reader, DateTime.MinValue, DateTime.MaxValue, logs[3], logs[1], logs[0]); // Infinite range, includes all. // function instance entry from the table we deleted is now missing. var entry2 = await reader.LookupFunctionInstanceAsync(logs[2].FunctionInstanceId); Assert.Null(entry2); }
private void ImportDodiInfo() { var businessManagement = new BusinessManagement(); //var document = new HtmlAgilityPack.HtmlDocument(); //document.LoadHtml(File.ReadAllText(@"D:\Badoucai\Dodi\2363\2363038\Mian_2363038.txt")); //var userInfo = businessManagement.FormatUserInfomation(document); //var business = businessManagement.FormatBusiness(document); var pathQueue = new ConcurrentQueue <string>(); var filePathQueue = new ConcurrentQueue <string>(); var count = 0; var index = 0; var pathList = Directory.GetDirectories(@"D:\Badoucai\Dodi\").ToList(); //pathList.Reverse(); pathList.ForEach(t => pathQueue.Enqueue(t)); Task.Run(() => { while (true) { if (filePathQueue.Count > 1000) { continue; } string path; if (!pathQueue.TryDequeue(out path)) { continue; } var files = Directory.GetFiles(path, "*", SearchOption.AllDirectories); count += files.Length; files.ToList().ForEach(t => filePathQueue.Enqueue(t)); } }); for (var i = 0; i < 16; i++) { Task.Run(() => { while (true) { string path; if (!filePathQueue.TryDequeue(out path)) { continue; } try { var document = new HtmlAgilityPack.HtmlDocument(); document.LoadHtml(File.ReadAllText(path)); try { var userInfo = businessManagement.FormatUserInfomation(document); var business = businessManagement.FormatBusiness(document); using (var db = new MangningXssDBEntities()) { db.DodiUserInfomation.AddOrUpdate(a => a.Id, userInfo); db.DodiBusiness.AddOrUpdate(a => a.Id, business); try { db.TransactionSaveChanges(); } catch (Exception ex) { while (true) { if (ex.InnerException == null) { break; } ex = ex.InnerException; } Program.SetLog(this.tbx_Log, $"多迪信息SaveChanges异常!异常文件路径:{path}, {ex.Message}"); LogFactory.Warn($"多迪信息SaveChanges异常!异常文件路径:{path}, {ex.Message}"); } } } catch (Exception ex) { continue; } var indexTemp = Interlocked.Increment(ref index); var destPath = path.Replace("Dodi", "Dodi-Success"); var destDirectoryPath = Path.GetDirectoryName(destPath); if (!string.IsNullOrEmpty(destDirectoryPath) && !Directory.Exists(destDirectoryPath)) { Directory.CreateDirectory(destDirectoryPath); } if (File.Exists(destPath)) { File.Delete(destPath); } File.Move(path, destPath); RunInMainthread(() => { Program.SetLog(this.tbx_Log, $"导入成功!进度:{indexTemp}/{count} {Path.GetFileNameWithoutExtension(path)}"); }); } catch (Exception ex) { RunInMainthread(() => { Program.SetLog(this.tbx_Log, $"多迪信息导入异常!异常文件路径:{path}, {ex.Message}"); }); LogFactory.Warn($"多迪信息导入异常!异常文件路径:{path}, {ex.Message}{Environment.NewLine}{ex.StackTrace}"); } } }); } }
public ScriptParser(LogFactory logFactory) { _logger = logFactory.CreateLogger <ScriptParser>(); }
/// <summary> /// Gets the specified URI. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="request">The request.</param> /// <param name="responseFormat">The response format.</param> /// <param name="scResponse">The sc response.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">scResponse</exception> public virtual T Get <T>(HttpWebRequest request, ResponseFormat responseFormat, T scResponse) where T : class, IBaseResponse { if (scResponse == null) { throw new ArgumentNullException("scResponse"); } try { var sw = Stopwatch.StartNew(); using (var response = (HttpWebResponse)request.GetResponse()) { var stream = response.GetResponseStream(); sw.Stop(); if (stream != null) { var sReader = new StreamReader(stream); try { switch (responseFormat) { case ResponseFormat.Json: scResponse = DeserializeJsonResponse <T>(sReader.ReadToEnd()); break; case ResponseFormat.Xml: scResponse = DeserializeXmlResponse <T>(sReader.ReadToEnd()); break; } if (scResponse != null) { scResponse.Info = new SitecoreWebResponseInfo { Uri = request.RequestUri, ResponseTime = sw.Elapsed }; scResponse.StatusDescription = response.StatusDescription; LogFactory.Info(string.Format("{0}: {1} - {2}", request.Method, scResponse.Info.ResponseTime, scResponse.Info.Uri.PathAndQuery)); } else { LogFactory.Warn("Could not convert deserialized response to IBaseResponse"); } } catch (Exception ex) { LogFactory.Error("Error deserializing the web service response", ex); } } } } catch (WebException ex) { SetExceptionMetaData(ex, scResponse); if (ex.Response != null) { var response = (HttpWebResponse)ex.Response; if (scResponse != null) { scResponse.StatusCode = response.StatusCode; scResponse.StatusDescription = response.StatusDescription; } } else { if (scResponse != null) { scResponse.StatusCode = HttpStatusCode.InternalServerError; } } LogFactory.Error("Web exception encountered when accessing the web service", ex); } catch (Exception ex) { SetExceptionMetaData(ex, scResponse); if (scResponse != null) { scResponse.StatusCode = HttpStatusCode.InternalServerError; } LogFactory.Error("Error accessing the web service", ex); } return(scResponse); }
public void DownloadBusiness() { const string cookie = "PHPSESSID=j0lklef94l9akqabg41n3nqd93; Example_auth=f9d7XYivszgUGkEXygbytRrg8EzZWngyS25FZaKx1OSub%2FhBVliH; Hm_lvt_1360b6fe7fa346ff51189adc58afb874=1507336367,1507510768,1507596684,1507682510; Hm_lpvt_1360b6fe7fa346ff51189adc58afb874=1507705480"; //const string cookie = "UM_distinctid =15cf6de66fd4fc-0e30531a6-4349052c-13c680-15cf6de66fe4e6; Hm_lvt_e1afad506a9557a8f31d1de1999fcd1a=1498790390; 58tj_uuid=02d03c66-977d-44ab-8029-1bee93cbd6b6; new_uv=1; als=0; PHPSESSID=4r9h0edodfm96ttb032od6q8k2; Example_auth=09fdPd2UmwZG%2BnjYqr0CL%2FCKLkFCYXqSs7tPUqs9pswDpjwzf1FPP32GVy1y; Hm_lvt_1360b6fe7fa346ff51189adc58afb874=1507432911,1507510849,1507684063,1507856431; Hm_lpvt_1360b6fe7fa346ff51189adc58afb874=1507882066"; var queue = new ConcurrentQueue <int>(); //2329979 2366914 2338074 Task.Run(() => { if (!cbx_UpdateBySZ.Checked) { int maxId; using (var db = new MangningXssDBEntities()) { maxId = db.DodiBusiness.Max(x => x.Id) + 1; } var maxIdTemp = maxId + 300000; for (var i = maxId; i < maxIdTemp; i++) { queue.Enqueue(i); } } else { using (var db = new MangningXssDBEntities()) { var query = from a in db.DodiBusiness join b in db.DodiUserInfomation on a.Id equals b.BusinessId where a.BranchOffice.Contains("深圳") && a.CreateTime > new DateTime(2017, 10, 24) && !b.IsPost select a.Id; var businessIdArr = query.ToArray(); foreach (var id in businessIdArr) { queue.Enqueue(id); } } } }); var cookieContainer = cookie.Serialize("crm.dodi.cn"); HttpClientFactory.RequestForString($"http://crm.dodi.cn/index.php/Notice/index", HttpMethod.Get, null, cookieContainer); var taskList = new List <Task>(); for (var j = 0; j < 1; j++) { taskList.Add(Task.Run(() => { while (true) { int i; if (!queue.TryDequeue(out i)) { continue; } var response = HttpClientFactory.RequestForString($"http://crm.dodi.cn/index.php/Main/khxxy/business_id/{i}/source/false_note", HttpMethod.Get, null, cookieContainer); if (!response.IsSuccess) { RunInMainthread(() => { Program.SetLog(this.tbx_Log, $"ID:{i} 请求失败!{response.ErrorMsg}"); }); LogFactory.Warn($"ID:{i} 请求失败!{response.ErrorMsg}"); continue; } if (!response.Data.Contains("商 机 ID:")) { RunInMainthread(() => { Program.SetLog(this.tbx_Log, $"ID:{i} 商机为空!{response.ErrorMsg}"); }); LogFactory.Warn($"ID:{i} 商机为空!{response.ErrorMsg}"); continue; //break; } var path = $@"D:\Badoucai\Dodi\{i.ToString().Substring(0, 4)}\{i}"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } File.WriteAllText($@"{path}\Mian_{i}.txt", response.Data); RunInMainthread(() => { Program.SetLog(this.tbx_Log, $"ID:{i} 下载成功!{response.ErrorMsg}"); }); Thread.Sleep(500); } })); } Task.WaitAll(taskList.ToArray()); RunInMainthread(() => { this.btn_Download.Text = "下载完成"; this.btn_Download.Enabled = true; }); }
/// <summary> /// Initializes a new instance of the <see cref="CachedRestorer"/> class. /// </summary> /// <param name="restorer">The <see cref="IRestorer"/> to be used when we miss the cache.</param> /// <param name="logFactory">The <see cref="LogFactory"/> to be used for logging.</param> public CachedRestorer(IRestorer restorer, LogFactory logFactory) { _restorer = restorer; _logger = logFactory.CreateLogger <CachedRestorer>(); }
public ScriptCompiler(LogFactory logFactory, bool useRestoreCache) : this(logFactory, new RuntimeDependencyResolver(logFactory, useRestoreCache)) { }
private int Mount(string passPhrase, IList <string> userNames) { var mountSection = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).Sections[MountSection.Name] as MountSection; if (mountSection == null) { throw new ConfigurationErrorsException("Mount configuration missing"); } settingsPassPhrase = passPhrase; var factory = InitializeCloudDriveFactory(mountSection.LibPath); try { using (var logFactory = new LogFactory()) { var logger = logFactory.GetCurrentClassLogger(); using (var tokenSource = new CancellationTokenSource()) { var tasks = new List <Task>(); foreach (var driveElement in mountSection.Drives.Where(d => !userNames.Any() || userNames.Contains(d.UserName))) { var drive = factory.CreateCloudDrive(driveElement.Schema, driveElement.UserName, driveElement.Root, new CloudDriveParameters() { EncryptionKey = driveElement.EncryptionKey, Parameters = driveElement.GetParameters() }); if (!drive.TryAuthenticate()) { var displayRoot = drive.DisplayRoot; drive.Dispose(); logger.Warn($"Authentication failed for drive '{displayRoot}'"); continue; } var operations = new CloudOperations(drive, logger); // HACK: handle non-unique parameter set of DokanOperations.Mount() by explicitely specifying AllocationUnitSize and SectorSize tasks.Add(Task.Run(() => operations.Mount(driveElement.Root, DokanOptions.RemovableDrive | DokanOptions.MountManager | DokanOptions.CurrentSession, mountSection.Threads, 1100, TimeSpan.FromSeconds(driveElement.Timeout != 0 ? driveElement.Timeout : 20), null, 512, 512), tokenSource.Token)); var driveInfo = new DriveInfo(driveElement.Root); while (!driveInfo.IsReady) { Thread.Sleep(10); } } Console.WriteLine("Press any key to unmount drives"); Console.ReadKey(true); tokenSource.Cancel(); return(0); } } } catch (Exception ex) { Console.Error.WriteLine($"{ex.GetType().Name}: {ex.Message}"); return(-1); } finally { foreach (var driveElement in mountSection.Drives.Cast <DriveElement>()) { Dokan.Unmount(driveElement.Root[0]); } UIThread.Shutdown(); } }
public XmlLoggingConfiguration([NotNull] XmlReader reader, [CanBeNull] string fileName, bool ignoreErrors, LogFactory logFactory) : base(logFactory) { Initialize(reader, fileName, ignoreErrors); }
private void ExportCD() { var cellphones = File.ReadAllLines(@"D:\给过的手机号-副本.txt"); using (var db = new MangningXssDBEntities()) { var beginDataTime = DateTime.Today.AddDays(-4); var endDataTime = DateTime.Today.AddDays(1); var dataList = db.DodiBusiness .Join(db.DodiUserInfomation, a => a.Id, b => b.BusinessId, (B, A) => new { B.Id, A.UserName, A.GraduatedSchool, B.BranchOffice, A.Email, A.Cellphone, B.CreateTime, B.Sources, A.JobName, B.PromoteBrand, A.ProfessionalTitle }) .Where(w => /*!w.BranchOffice.StartsWith("北京") && !w.BranchOffice.StartsWith("上海") && !w.BranchOffice.StartsWith("广州") && */ w.BranchOffice.StartsWith("成都") && w.CreateTime > beginDataTime && w.CreateTime < endDataTime) .Select(s => new { s.Id, s.UserName, s.Cellphone, s.Email, s.Sources, s.CreateTime, s.JobName, s.ProfessionalTitle }) .ToList(); const string cookie = "PHPSESSID=j0lklef94l9akqabg41n3nqd93; Example_auth=f9d7XYivszgUGkEXygbytRrg8EzZWngyS25FZaKx1OSub%2FhBVliH; Hm_lvt_1360b6fe7fa346ff51189adc58afb874=1507336367,1507510768,1507596684,1507682510; Hm_lpvt_1360b6fe7fa346ff51189adc58afb874=1507705480"; var cookieContainer = cookie.Serialize("crm.dodi.cn"); HttpClientFactory.RequestForString("http://crm.dodi.cn/index.php/Notice/index", HttpMethod.Get, null, cookieContainer); var sb = new StringBuilder(); sb.AppendLine("姓名\t手机\t邮箱\t年龄\t学历\t更新日期\t性别\t平台\t地点\t职位\t专业"); var index = 0; foreach (var item in dataList) { var response = HttpClientFactory.RequestForString($"http://crm.dodi.cn/index.php/Main/khxxy/business_id/{item.Id}/source/false_note", HttpMethod.Get, null, cookieContainer); if (!response.IsSuccess) { RunInMainthread(() => { Program.SetLog(this.tbx_Log, $"ID:{item.Id} 请求失败!{response.ErrorMsg}"); }); LogFactory.Warn($"ID:{item.Id} 请求失败!{response.ErrorMsg}"); continue; } if (!response.Data.Contains("商 机 ID:")) { RunInMainthread(() => { Program.SetLog(this.tbx_Log, $"ID:{item.Id} 商机为空!{response.ErrorMsg}"); }); LogFactory.Warn($"ID:{item.Id} 商机为空!{response.ErrorMsg}"); continue; } var match = Regex.Match(response.Data, @"resume_email\('(.*?)','(\d+)','(\d+)','(\d+)',(\d+)\)"); if (!match.Success) { RunInMainthread(() => { Program.SetLog(this.tbx_Log, $"ID:{item.Id} 匹配详情失败!"); }); LogFactory.Warn($"ID:{item.Id} 匹配详情失败!"); continue; } var email = HttpUtility.UrlEncode(match.Result("$1")); var phone = HttpUtility.UrlEncode(match.Result("$2")); var email_id = HttpUtility.UrlEncode(match.Result("$3")); var now_month = HttpUtility.UrlEncode(match.Result("$4")); var school_id = HttpUtility.UrlEncode(match.Result("$5")); if (cellphones.Contains(phone)) { continue; } response = HttpClientFactory.RequestForString($"http://crm.dodi.cn/index.php/Main/email_body?email={email}&phone={phone}&email_id={email_id}&now_month={now_month}&school_id={school_id}", HttpMethod.Get, null, cookieContainer); if (!response.IsSuccess) { RunInMainthread(() => { Program.SetLog(this.tbx_Log, $"ID:{item.Id} 详情请求失败!{response.ErrorMsg}"); }); LogFactory.Warn($"ID:{item.Id} 详情请求失败!{response.ErrorMsg}"); continue; } //File.WriteAllText($@"D:\Business\{item.Id}.txt", response.Data); var data = Regex.Unescape(response.Data); var xbMatch = Regex.Match(data, "(男|女)"); if (xbMatch.Value.Trim() == "女") { continue; } var ageMatch = Regex.Match(data, "((?<=[^0-9])[0-9]{2}岁|年龄\\s*[0-9]{2}(?=[^0-9]))"); if (!ageMatch.Success) { ageMatch = Regex.Match(data, "(19|20)[0-9]{2}(年|-)[0-9]{1,2}(月|)(?=[^0-9])"); } //var xlMatch = Regex.Match(data, "(高中|初中|小学|大专|中专)"); var xlMatch = Regex.Match(data, "(大专|本科|硕士|博士|MBA)"); //var date = item.CreateTime < DateTime.Today.AddDays(-3) ? item.CreateTime?.AddDays(2) : item.CreateTime; sb.AppendLine($"{item.UserName}\t{item.Cellphone}\t{item.Email}\t{ageMatch.Value}\t{xlMatch.Value}\t{item.CreateTime?.ToString("yyyy-MM-dd")}\t{xbMatch.Value}\t{item.Sources.Substring(item.Sources.LastIndexOf("_", StringComparison.Ordinal) + 1)}\t成都\t{item.JobName}\t{item.ProfessionalTitle}"); //sb.AppendLine($"{item.Cellphone}"); //if (index % 1000 == 0) //{ // File.WriteAllText(@"D:\非北上广.txt", sb.ToString()); //} RunInMainthread(() => { Program.SetLog(this.tbx_Log, $"{Interlocked.Increment(ref index)}/{dataList.Count}"); }); } ; File.WriteAllText(@"D:\成都大专以上.txt", sb.ToString()); } }
public AbstractInitiator(Application app, MessageStoreFactory storeFactory, SessionSettings settings, LogFactory logFactory) : this(app, storeFactory, settings, logFactory, null) { }
public void ReloadConfigOnTimer_DoesNotThrowConfigException_IfConfigChangedInBetween() { var loggingConfiguration = new LoggingConfiguration(); LogManager.Configuration = loggingConfiguration; var logFactory = new LogFactory(loggingConfiguration); var differentConfiguration = new LoggingConfiguration(); Assert.DoesNotThrow(() => logFactory.ReloadConfigOnTimer(differentConfiguration)); }
public async Task LogExactWriteAndRead() { // Make some very precise writes and verify we read exactly what we'd expect. ILogWriter writer = LogFactory.NewWriter(DefaultHost, "c1", this); ILogReader reader = LogFactory.NewReader(this); string Func1 = "alpha"; string Func2 = "beta"; var t1a = new DateTime(2010, 3, 6, 10, 11, 20); var t1b = new DateTime(2010, 3, 6, 10, 11, 21); // same time bucket as t1a var t2 = new DateTime(2010, 3, 7, 10, 11, 21); FunctionInstanceLogItem l1 = new FunctionInstanceLogItem { FunctionInstanceId = Guid.NewGuid(), FunctionName = Func1, StartTime = t1a, LogOutput = "one" }; await WriteAsync(writer, l1); await writer.FlushAsync(); // Multiple flushes; test starting & stopping the backgrounf worker. FunctionInstanceLogItem l2 = new FunctionInstanceLogItem { FunctionInstanceId = Guid.NewGuid(), FunctionName = Func2, StartTime = t1b, LogOutput = "two" }; await WriteAsync(writer, l2); FunctionInstanceLogItem l3 = new FunctionInstanceLogItem { FunctionInstanceId = Guid.NewGuid(), FunctionName = Func1, StartTime = t2, LogOutput = "three", ErrorDetails = "this failed" }; await WriteAsync(writer, l3); await writer.FlushAsync(); // Now read var definitionSegment = await reader.GetFunctionDefinitionsAsync(null, null); string[] functionNames = Array.ConvertAll(definitionSegment.Results, definition => definition.Name); Array.Sort(functionNames); Assert.Equal(Func1, functionNames[0]); Assert.Equal(Func2, functionNames[1]); // Read Func1 { var segment1 = await reader.GetAggregateStatsAsync(l3.FunctionId, DateTime.MinValue, DateTime.MaxValue, null); Assert.Null(segment1.ContinuationToken); var stats1 = segment1.Results; Assert.Equal(2, stats1.Length); // includes t1 and t2 // First bucket has l1, second bucket has l3 Assert.Equal(stats1[0].TotalPass, 1); Assert.Equal(stats1[0].TotalRun, 1); Assert.Equal(stats1[0].TotalFail, 0); Assert.Equal(stats1[1].TotalPass, 0); Assert.Equal(stats1[1].TotalRun, 1); Assert.Equal(stats1[1].TotalFail, 1); // reverse order. So l3 latest function, is listed first. var recent1 = await GetRecentAsync(reader, l3.FunctionId); Assert.Equal(2, recent1.Length); Assert.Equal(recent1[0].FunctionInstanceId, l3.FunctionInstanceId); Assert.Equal(recent1[1].FunctionInstanceId, l1.FunctionInstanceId); } // Read Func2 { var segment2 = await reader.GetAggregateStatsAsync(l2.FunctionId, DateTime.MinValue, DateTime.MaxValue, null); var stats2 = segment2.Results; Assert.Equal(1, stats2.Length); Assert.Equal(stats2[0].TotalPass, 1); Assert.Equal(stats2[0].TotalRun, 1); Assert.Equal(stats2[0].TotalFail, 0); var recent2 = await GetRecentAsync(reader, l2.FunctionId); Assert.Equal(1, recent2.Length); Assert.Equal(recent2[0].FunctionInstanceId, l2.FunctionInstanceId); } }
public void ReloadConfigOnTimer_Raises_ConfigurationReloadedEvent() { var called = false; var loggingConfiguration = new LoggingConfiguration(); LogManager.Configuration = loggingConfiguration; var logFactory = new LogFactory(loggingConfiguration); logFactory.ConfigurationReloaded += (sender, args) => { called = true; }; logFactory.ReloadConfigOnTimer(loggingConfiguration); Assert.True(called); }
public async Task DifferentHosts() { // 1a & 1b are 2 instances (different machines) of the same host. They share. // 2 is a separate host. string host1 = "h1-1"; // includes an tricky character that requires escaping. string host2 = "h22"; ILogWriter writer1a = LogFactory.NewWriter(host1, "c1", this); ILogWriter writer1b = LogFactory.NewWriter(host1, "c2", this); ILogWriter writer2 = LogFactory.NewWriter(host2, "c3", this); ILogReader reader1 = LogFactory.NewReader(this); ILogReader reader2 = LogFactory.NewReader(this); string Func1 = "alpha"; var f1a = await QuickWriteAsync(writer1a, Func1); // first var f1b = await QuickWriteAsync(writer1b, Func1); var f1aa = await QuickWriteAsync(writer1a, Func1); // second write var f2 = await QuickWriteAsync(writer2, Func1); // Verify readers // Function definitions. Search all hosts if no host specified { var segment = await reader1.GetFunctionDefinitionsAsync(null, null); Assert.Equal(2, segment.Results.Length); var allDefinitions = segment.Results; segment = await reader1.GetFunctionDefinitionsAsync(host1, null); Assert.Equal(1, segment.Results.Length); var host1Defs = segment.Results[0]; Assert.Equal(Func1, host1Defs.Name); Assert.Equal(FunctionId.Build(host1, Func1), host1Defs.FunctionId); segment = await reader1.GetFunctionDefinitionsAsync(host2, null); Assert.Equal(1, segment.Results.Length); var host2Defs = segment.Results[0]; Assert.Equal(Func1, host2Defs.Name); Assert.Equal(FunctionId.Build(host2, Func1), host2Defs.FunctionId); Assert.Equal(Func1, allDefinitions[0].Name); Assert.Equal(Func1, allDefinitions[1].Name); Assert.Equal(host1Defs.FunctionId, allDefinitions[0].FunctionId); Assert.Equal(host2Defs.FunctionId, allDefinitions[1].FunctionId); } // Recent list { var segment = await reader1.GetRecentFunctionInstancesAsync(new RecentFunctionQuery { FunctionId = FunctionId.Build(host1, Func1), End = DateTime.MaxValue, }, null); Guid[] guids = Array.ConvertAll(segment.Results, x => x.FunctionInstanceId); Assert.Equal(3, guids.Length); // Only include host 1 Assert.Equal(f1a, guids[2]); // reverse chronological Assert.Equal(f1b, guids[1]); Assert.Equal(f1aa, guids[0]); } // cross polination. Lookup across hosts. { var entry = await reader2.LookupFunctionInstanceAsync(f1a); Assert.NotNull(entry); Assert.Equal(entry.FunctionName, Func1); } }
public void ReloadConfigOnTimer_When_No_Exception_Raises_ConfigurationReloadedEvent_With_Argument_Indicating_Success() { LoggingConfigurationReloadedEventArgs arguments = null; var loggingConfiguration = new LoggingConfiguration(); LogManager.Configuration = loggingConfiguration; var logFactory = new LogFactory(loggingConfiguration); logFactory.ConfigurationReloaded += (sender, args) => { arguments = args; }; logFactory.ReloadConfigOnTimer(loggingConfiguration); Assert.True(arguments.Succeeded); }
public JsonResult SaveAuth(long groupId, GroupAuthModel[] models) { var apiResult = new APIResult(); if (groupId == 1) { apiResult.Ret = -1; apiResult.Msg = "不可设置平台管理员权限"; return(Json(apiResult)); } List <GroupAuthority> authList = new List <GroupAuthority>(); if (models.Length == 0) { apiResult.Ret = -1; apiResult.Msg = "请选择权限"; return(Json(apiResult)); } //获取所有菜单 var menuList = MenuBll.GetMenus(); //获取所有按钮 var btnList = FuncBtnBll.GetList(); try { foreach (var item in models) { long menuId = item.id; var menu = menuList.FirstOrDefault(m => m.Id == menuId); if (menu == null) { continue; } string btnsStr = item.btnIdStr; if (string.IsNullOrWhiteSpace(btnsStr)) { continue; } string[] btnIdArray = btnsStr.Split(','); if (btnIdArray.Length == 0) { continue; } foreach (var btnIdString in btnIdArray) { long btnId = 0; if (long.TryParse(btnIdString, out btnId)) { var funcBtn = btnList.FirstOrDefault(m => m.Id == btnId); authList.Add(new GroupAuthority() { GroupId = groupId, MenuId = menuId, MenuController = menu.MenuController, FuncBtnId = funcBtn.Id, FuncBtnName = funcBtn.Name, FuncBtnCode = funcBtn.Code, Seq = funcBtn.Seq, CDate = TypeConvert.DateTimeToInt(DateTime.Now) }); } } } if (authList.Count == 0) { GroupAuthorityBll.Delete(groupId); } else { GroupAuthorityBll.Delete(groupId); authList.ForEach(m => { GroupAuthorityBll.AddOrUpdate(m); }); } } catch (Exception ex) { apiResult.Ret = -1; apiResult.Msg = ex.Message; if (!(ex is OperationExceptionFacade)) { LogFactory.GetLogger().Log(LogLevel.Error, ex); } } return(Json(apiResult)); }
public void SuspendAndResumeLogging_OutOfOrder() { LogFactory factory = new LogFactory(); // Out of order Resume => Suspend => (Suspend => Resume) factory.ResumeLogging(); Assert.True(factory.IsLoggingEnabled()); factory.SuspendLogging(); Assert.True(factory.IsLoggingEnabled()); factory.SuspendLogging(); Assert.False(factory.IsLoggingEnabled()); factory.ResumeLogging(); Assert.True(factory.IsLoggingEnabled()); }
/// <summary> /// /// </summary> /// <param name="app"></param> /// <param name="logFactory"></param> /// <returns></returns> public static IAppBuilder UseLoggingMiddleware(this IAppBuilder app, LogFactory logFactory) { app.Use <LoggingMiddleware>(logFactory); return(app); }
static rest_client_tests() { var lf = LogFactory.Create().AddUnbufferedConsole(); _client = new RestClient(lf, 100); }
/// <summary> /// 上传智联 Josn 格式简历 /// </summary> /// <param name="json"></param> /// <param name="jsonResumeId"></param> /// <returns></returns> public DataResult UploadZhaopinResume(string json, int jsonResumeId) { try { var resumeData = JsonConvert.DeserializeObject <dynamic>(json); var resumeDetail = JsonConvert.DeserializeObject(resumeData.detialJSonStr.ToString()); var refreshTime = BaseFanctory.GetTime((string)resumeDetail.DateLastReleased).ToUniversalTime(); resumeData.detialJSonStr = resumeDetail; var resumeNumber = ((string)resumeData.resumeNo).Substring(0, 10); var userId = (int)resumeData.userDetials.userMasterId; var resumeId = resumeData.resumeId != null ? (int)resumeData.resumeId : resumeDetail.ResumeId != null ? (int)resumeDetail.ResumeId : 0; using (var db = new MangningXssDBEntities()) { var resume = db.ZhaopinResume.FirstOrDefault(f => f.Id == resumeId); if (!(resume?.RefreshTime != null && resume.RefreshTime.Value.Date >= refreshTime.Date)) { if (resume != null) { resume.RandomNumber = resumeNumber; resume.RefreshTime = refreshTime; resume.UpdateTime = DateTime.UtcNow; if (string.IsNullOrEmpty(resume.UserExtId)) { resume.UserExtId = resumeDetail.UserMasterExtId.ToString(); } resume.Source = !resume.Source.Contains("Download") ? resume.Source += ",Download" : resume.Source; resume.Flag = 0xE; } else { resume = new ZhaopinResume { Id = resumeId, RandomNumber = resumeNumber, UserId = userId, RefreshTime = refreshTime, UpdateTime = DateTime.UtcNow, UserExtId = resumeDetail.UserMasterExtId.ToString(), DeliveryNumber = null, Source = "Download", Flag = 0xE }; db.ZhaopinResume.Add(resume); } var user = db.ZhaopinUser.FirstOrDefault(f => f.Id == userId); if (user != null) { if (!user.Source.Contains("MANUAL")) { user.ModifyTime = BaseFanctory.GetTime((string)resumeDetail.DateModified).ToUniversalTime(); user.CreateTime = BaseFanctory.GetTime((string)resumeDetail.DateCreated).ToUniversalTime(); user.Cellphone = resumeData.userDetials.mobilePhone.ToString(); user.Email = resumeData.userDetials.email.ToString(); user.Name = resumeData.userDetials.userName.ToString(); user.UpdateTime = DateTime.UtcNow; user.Username = resumeData.userDetials.email.ToString(); } } else { user = new ZhaopinUser { Id = userId, Source = "Download", ModifyTime = BaseFanctory.GetTime((string)resumeDetail.DateModified).ToUniversalTime(), CreateTime = BaseFanctory.GetTime((string)resumeDetail.DateCreated).ToUniversalTime(), Cellphone = resumeData.userDetials.mobilePhone.ToString(), Email = resumeData.userDetials.email.ToString(), Name = resumeData.userDetials.userName.ToString(), UpdateTime = DateTime.UtcNow, Username = resumeData.userDetials.email.ToString() }; db.ZhaopinUser.Add(user); } var resumeContent = JsonConvert.SerializeObject(resumeData); using (var jsonStream = new MemoryStream(GZip.Compress(Encoding.UTF8.GetBytes(resumeContent)))) { mangningOssClient.PutObject(mangningBucketName, $"Zhaopin/Resume/{resumeId}", jsonStream); } var resumePath = $"{uploadFilePath}{resumeId}.json"; File.WriteAllText(resumePath, JsonConvert.SerializeObject(resumeData)); db.SaveChanges(); } } return(new DataResult()); } catch (Exception ex) { LogFactory.Warn($"简历上传异常!异常信息:{ex.Message}, Json:{json}"); return(new DataResult { ErrorMsg = $"Josn 格式异常,resumeNo:{jsonResumeId},{ex.Message}", IsSuccess = false }); } }
public PixabayService() { logger = LogFactory.GetLogger("pixabay"); }
/// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param> /// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param> /// <param name="ignoreErrors">Ignore any errors during configuration.</param> /// <param name="logFactory">The <see cref="LogFactory" /> to which to apply any applicable configuration values.</param> public XmlLoggingConfiguration(XmlReader reader, string fileName, bool ignoreErrors, LogFactory logFactory) { this.logFactory = logFactory; this.Initialize(reader, fileName, ignoreErrors); }
private static NLogLoggerProvider CreateNLogLoggerProvider(IServiceProvider serviceProvider, IConfiguration configuration, NLogProviderOptions options, LogFactory logFactory) { NLogLoggerProvider provider = new NLogLoggerProvider(options ?? NLogProviderOptions.Default, logFactory ?? LogManager.LogFactory); configuration = SetupConfiguration(serviceProvider, configuration); if (configuration != null && options == null) { provider.Configure(configuration.GetSection("Logging:NLog")); } return(provider); }
/// <summary> /// Initializes a new instance of the <see cref="LogReceiverOneWayForwardingService"/> class. /// </summary> /// <param name="logFactory">The log factory.</param> public LogReceiverOneWayForwardingService(LogFactory logFactory) : base(logFactory) { }
/// <summary> /// 设置配置文件 /// </summary> /// <param name="configuration"></param> /// <param name="configPath">配置文件路径</param> /// <returns></returns> public static void Configure(string configPath) { LogFactory factory = NLog.Web.NLogBuilder.ConfigureNLog(configPath); NLogContext.Configure(factory); }
/// <summary> /// Initializes a new instance of the <see cref="LogReceiverForwardingService"/> class. /// </summary> /// <param name="logFactory">The log factory.</param> public LogReceiverForwardingService(LogFactory logFactory) { this.logFactory = logFactory; }
void Awake() { #if UNITY_SERVER LogFactory.ReplaceLogHandler(new ConsoleColorLogHandler(showExceptionStackTrace)); #endif }
public void DownloadAnonymousResumes() { //const string cookie = "PHPSESSID=cl79f305e8fv4kfq5eijcf3376; Hm_lvt_3c8ecbfa472e76b0340d7a701a04197e=1509065458,1509099221,1509324837,1509411160; Hm_lpvt_3c8ecbfa472e76b0340d7a701a04197e=1509427603; Hm_lvt_407473d433e871de861cf818aa1405a1=1509065458,1509099221,1509324837,1509411160; Hm_lpvt_407473d433e871de861cf818aa1405a1=1509427603; think_language=zh-cn"; const string cookie = "UM_distinctid =15cf6de66fd4fc-0e30531a6-4349052c-13c680-15cf6de66fe4e6; Hm_lvt_e1afad506a9557a8f31d1de1999fcd1a=1498790390; 58tj_uuid=02d03c66-977d-44ab-8029-1bee93cbd6b6; new_uv=1; als=0; PHPSESSID=4r9h0edodfm96ttb032od6q8k2; Example_auth=09fdPd2UmwZG%2BnjYqr0CL%2FCKLkFCYXqSs7tPUqs9pswDpjwzf1FPP32GVy1y; Hm_lvt_1360b6fe7fa346ff51189adc58afb874=1507432911,1507510849,1507684063,1507856431; Hm_lpvt_1360b6fe7fa346ff51189adc58afb874=1507882066"; var cookieContainer = cookie.Serialize("120.77.152.11"); var queue = new ConcurrentQueue <int>(); Task.Run(() => { for (var i = 1; i < 1; i++) { var response = HttpClientFactory.RequestForString($"http://120.77.152.11/index.php?m=leads&listrows=100&p={i}", HttpMethod.Get, null, cookieContainer); if (!response.IsSuccess) { RunInMainthread(() => { Program.SetLog(this.tbx_Log, $"请求失败!{response.ErrorMsg}"); }); continue; } var matchs = Regex.Matches(response.Data, "<a href=\"/index\\.php\\?m=leads&a=view&id=(\\d+)\">"); foreach (Match match in matchs) { queue.Enqueue(Convert.ToInt32(match.Result("$1"))); } } }); var taskList = new List <Task>(); for (var j = 0; j < 1; j++) { taskList.Add(Task.Run(() => { while (true) { int i; if (!queue.TryDequeue(out i)) { continue; } var response = HttpClientFactory.RequestForString($"http://120.77.152.11/index.php?m=leads&a=view&id={i}", HttpMethod.Get, null, cookieContainer); if (!response.IsSuccess) { RunInMainthread(() => { Program.SetLog(this.tbx_Log, $"ID:{i} 请求失败!{response.ErrorMsg}"); }); LogFactory.Warn($"ID:{i} 请求失败!{response.ErrorMsg}"); continue; } const string path = @"D:\Badoucai\AnonymousResumes"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } File.WriteAllText($@"{path}\Mian_{i}.txt", response.Data); RunInMainthread(() => { Program.SetLog(this.tbx_Log, $"ID:{i} 下载成功!{response.ErrorMsg}"); }); } })); } Task.WaitAll(taskList.ToArray()); }
public void TestLibraryLogger() { LogFactory.CreateLogger().Write(LogSeverity.SystemInformation, "Logging!"); }
public void ReloadConfigOnTimer_DoesNotThrowConfigException_IfConfigReloadReturnsNull() { var loggingConfiguration = new ReloadNullConfiguration(); LogManager.Configuration = loggingConfiguration; var logFactory = new LogFactory(loggingConfiguration); Assert.DoesNotThrow(() => logFactory.ReloadConfigOnTimer(loggingConfiguration)); }
private CompilationDependencyResolver(ScriptProjectProvider scriptProjectProvider, ScriptDependencyInfoProvider scriptDependencyInfoProvider, ScriptFilesDependencyResolver scriptFilesDependencyResolver, LogFactory logFactory) { _scriptProjectProvider = scriptProjectProvider; _scriptDependencyInfoProvider = scriptDependencyInfoProvider; _scriptFilesDependencyResolver = scriptFilesDependencyResolver; _logger = logFactory.CreateLogger <CompilationDependencyResolver>(); }
public void ReloadConfigOnTimer_When_No_Exception_Raises_ConfigurationReloadedEvent_With_Correct_Sender() { object calledBy = null; var loggingConfiguration = new LoggingConfiguration(); LogManager.Configuration = loggingConfiguration; var logFactory = new LogFactory(loggingConfiguration); logFactory.ConfigurationReloaded += (sender, args) => { calledBy = sender; }; logFactory.ReloadConfigOnTimer(loggingConfiguration); Assert.Same(calledBy, logFactory); }
private static IRestorer CreateRestorer(LogFactory logFactory) { var commandRunner = new CommandRunner(logFactory); return(new ProfiledRestorer(new DotnetRestorer(commandRunner, logFactory), logFactory)); }
public void SuspendAndResumeLogging_InOrder() { LogFactory factory = new LogFactory(); // In order Suspend => Resume [Case 1] Assert.True(factory.IsLoggingEnabled()); factory.SuspendLogging(); Assert.False(factory.IsLoggingEnabled()); factory.ResumeLogging(); Assert.True(factory.IsLoggingEnabled()); // In order Suspend => Resume [Case 2] using (var factory2 = new LogFactory()) { Assert.True(factory.IsLoggingEnabled()); factory.SuspendLogging(); Assert.False(factory.IsLoggingEnabled()); factory.ResumeLogging(); Assert.True(factory.IsLoggingEnabled()); } }
public static void AssertDebugLastMessage(this LogFactory logFactory, string message) { AssertDebugLastMessage(logFactory, "Debug", message); }
private void AssertMessageFormattedWithCulture(LoggingConfiguration configuration, CultureInfo culture, string formatString, params object[] parameters) { var expected = string.Format(culture, formatString, parameters); using (var logFactory = new LogFactory(configuration)) { var logger = logFactory.GetLogger("test"); logger.Debug(formatString, parameters); Assert.Equal(expected, GetDebugLastMessage("debug", configuration)); } }
public static void AssertDebugLastMessage(this LogFactory logFactory, string targetName, string message) { var debugTarget = GetDebugTarget(targetName, logFactory.Configuration); Assert.Equal(message, debugTarget.LastMessage); }