I'm working on ASP.Net MVC web app, using System.Diagnostics.TraceSource to trace and log to file. Added following to web.config
<system.diagnostics>
<trace autoflush="false" indentsize="4"></trace> // what's this for?
<sources>
<source name ="WebAppLog">
<listeners>
<add name="FileLog" type="System.Diagnostics.TextWriterTraceListener" initializeData="PartialView_WebApp.log" traceOutputOptions="DateTime,ThreadId,ProcessId,Timestamp,LogicalOperationStack,Callstack">
<filter initializeData="All" type="System.Diagnostics.EventTypeFilter"/>
</add>
<remove name="Default"/>
</listeners>
</source>
</sources>
</system.diagnostics>
Added Log.cs to application to log mesages to file.
public class Log
{
static TraceSource source = new TraceSource("WebAppLog");
public static void Message(TraceEventType traceEventType, string message)
{
short id;
switch (traceEventType)
{
case TraceEventType.Information:
id = 3;
break;
case TraceEventType.Verbose:
id = 4;
break;
default:
id = -1;
break;
}
source.TraceEvent(traceEventType, id, message);
source.Flush();
}
}
Home controller.cs
public ActionResult Index()
{
try
{
Log.Message(System.Diagnostics.TraceEventType.Information, "Index Action Start");
// Do work
Log.Message(System.Diagnostics.TraceEventType.Information, "Index Action End");
return View();
}
catch (Exception ex)
{
throw;
}
}
After executing, i'm able to generate log file but couldn't write anything, always the file size is 0 bytes. What could be the possible mistake.?
The Switch on a TraceSource determines whether any output gets generated.
By default, if it is not configured, there will be no output.
The value for the Switch matches the log levels that should appear in the output.
It can be set via code:
static TraceSource source = new TraceSource("WebAppLog");
source.Switch.Level = SourceLevels.Verbose;
Or via configuration, which is more flexible.
Your configuration will look like:
<system.diagnostics>
<trace autoflush="false" indentsize="4"></trace>
<sources>
<source name ="WebAppLog" switchName="mySwitch">
<listeners>
<add name="FileLog" type="System.Diagnostics.TextWriterTraceListener" initializeData="c:\tmp\trace.log" traceOutputOptions="DateTime,ThreadId,ProcessId,Timestamp,LogicalOperationStack,Callstack">
<filter initializeData="All" type="System.Diagnostics.EventTypeFilter"/>
</add>
<remove name="Default"/>
</listeners>
</source>
</sources>
<switches>
<add name="mySwitch" value="Verbose" />
</switches>
</system.diagnostics>
Regarding your question about
<trace autoflush="false" indentsize="4"></trace>
With autoflush=true you don't have to call source.Flush() explicitly.
The indentsize gets applied in the log output, notice the leading whitespace starting from line 2 in the output fragment below.
WebAppLog Information: 3: Index Action Start
ProcessId=7416
LogicalOperationStack=
ThreadId=1
Related
I have a component that is used by different applications.
In this component we might need logging so I thought I'd use an EventSource.
The component is netstandard2.0, the application using the component is .NET Framework 4.6.1.
This is what I have so far in my component:
public class XEvents
{
public const int BeforeSendingRequest = 1;
public const int AfterSendingRequest = 2;
}
[EventSource(Name = "XEventSource")]
public class XEventSource : EventSource
{
public static XEventSource Log = new XEventSource();
[Event(XEvents.BeforeSendingRequest, Message = "Request: {0}", Level = EventLevel.Verbose, Keywords = EventKeywords.WdiDiagnostic)]
public void BeforeSendingRequest(string request) { if (IsEnabled()) WriteEvent(XEvents.BeforeSendingRequest, request); }
[Event(XEvents.AfterSendingRequestToCsam, Message = "Response: {0}", Level = EventLevel.Verbose, Keywords = EventKeywords.WdiDiagnostic)]
public void AfterSendingRequest(string response) { if (IsEnabled()) WriteEvent(XEvents.AfterSendingRequest, response); }
}
And in the application I added the following to the app.config:
<system.diagnostics>
<sources>
<source name="NamespaceOfEventSource.XEventSource" switchValue="Verbose">
<listeners>
<add name="XEventSourceListener" />
</listeners>
</source>
</sources>
<sharedListeners>
<add name="XEventSourceListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="X.log" traceOutputOptions="ProcessId, DateTime" />
</sharedListeners>
<trace autoflush="true" />
</system.diagnostics>
But when I run the application there is no X.log inside the bin folder.
When I debug to the eventsource of the component I see that Enabled() returns false.
I suspect the listeners arent beeing bound to the EventSource. But I don't really see what I'm doing wrong.
Thanks in advance for any information you can give me!
I ended up using TraceSource instead of EventSource.
https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.tracesource?view=netcore-3.1
In our Website this error is come every 5 minutes.
And I don't know from where its call.
we need robots.txt without this error.
our application automatic call http://www.xyzName.com/content/images/thumbs/robots.txt
And show below exception
System.Web.Routing.UrlRoutingModule does not implement
IHttpHandlerFactory or IHttpHandler.
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
This is the method which automatic generate the robots.txt file when this method is call. but the problem is from some where in application robots.txt call automatically.
public ActionResult RobotsTextFile()
{
//Default Code blocked by Nilesh
if (_storeContext.CurrentStore.Url.Contains("tk"))
{
const string newLine = "\r\n"; //Environment.NewLine
var sb = new StringBuilder();
sb.Append("User-agent: *");
sb.Append(newLine);
sb.Append("Disallow: /");
Response.ContentType = "text/plain";
Response.Write(sb.ToString());
}
else
{
var disallowPaths = new List<string>
{
"/bin/",
"/content/files/",
"/content/files/exportimport/",
"/country/getstatesbycountryid",
"/install",
"/setproductreviewhelpfulness",
};
var localizableDisallowPaths = new List<string>
{
"/addproducttocart/catalog/",
"/addproducttocart/details/",
"/backinstocksubscriptions/manage",
"/boards/forumsubscriptions",
"/boards/forumwatch",
"/boards/postedit",
"/boards/postdelete",
"/boards/postcreate",
"/boards/topicedit",
"/boards/topicdelete",
"/boards/topiccreate",
"/boards/topicmove",
"/boards/topicwatch",
"/cart",
"/checkout",
"/checkout/billingaddress",
"/checkout/completed",
"/checkout/confirm",
"/checkout/shippingaddress",
"/checkout/shippingmethod",
"/checkout/paymentinfo",
"/checkout/paymentmethod",
"/clearcomparelist",
"/compareproducts",
"/customer/avatar",
"/customer/activation",
"/customer/addresses",
"/customer/changepassword",
"/customer/checkusernameavailability",
"/customer/downloadableproducts",
"/customer/info",
"/deletepm",
"/emailwishlist",
"/inboxupdate",
"/newsletter/subscriptionactivation",
"/onepagecheckout",
"/order/history",
"/orderdetails",
"/passwordrecovery/confirm",
"/poll/vote",
"/privatemessages",
"/returnrequest",
"/returnrequest/history",
"/rewardpoints/history",
"/sendpm",
"/sentupdate",
"/shoppingcart/productdetails_attributechange",
"/subscribenewsletter",
"/topic/authenticate",
"/viewpm",
"/uploadfileproductattribute",
"/uploadfilecheckoutattribute",
"/wishlist",
};
const string newLine = "\r\n"; //Environment.NewLine
var sb = new StringBuilder();
sb.Append("User-agent: *");
sb.Append(newLine);
//sitemaps
if (_localizationSettings.SeoFriendlyUrlsForLanguagesEnabled)
{
//URLs are localizable. Append SEO code
foreach (var language in _languageService.GetAllLanguages(storeId: _storeContext.CurrentStore.Id))
{
sb.AppendFormat("Sitemap: {0}{1}/sitemap.xml", _storeContext.CurrentStore.Url, language.UniqueSeoCode);
sb.Append(newLine);
}
}
else
{
//localizable paths (without SEO code)
sb.AppendFormat("Sitemap: {0}sitemap.xml", _storeContext.CurrentStore.Url);
sb.Append(newLine);
}
//usual paths
foreach (var path in disallowPaths)
{
sb.AppendFormat("Disallow: {0}", path);
sb.Append(newLine);
}
//localizable paths (without SEO code)
foreach (var path in localizableDisallowPaths)
{
sb.AppendFormat("Disallow: {0}", path);
sb.Append(newLine);
}
if (_localizationSettings.SeoFriendlyUrlsForLanguagesEnabled)
{
//URLs are localizable. Append SEO code
foreach (var language in _languageService.GetAllLanguages(storeId: _storeContext.CurrentStore.Id))
{
foreach (var path in localizableDisallowPaths)
{
sb.AppendFormat("Disallow: {0}{1}", language.UniqueSeoCode, path);
sb.Append(newLine);
}
}
}
Response.ContentType = "text/plain";
Response.Write(sb.ToString());
}
return null;
}
And In RouteProvider we add below line to map the route.
routes.MapRoute("robots.txt","robots.txt",new { controller = "Common", action ="RobotsTextFile" },new[] { "Nop.Web.Controllers" });
It comes in every 5 minuets. we use amazon server for CDN, get Images from there.
Is there any possibility that amazon called this 'http://www.xyzName.com/content/images/thumbs/robots.txt' url?
Remove (or comment out) this line from your web.config For generating robot.txt
<add name="RobotsTxt" path="robots.txt" verb="*" type="System.Web.Routing.UrlRoutingModule" resourceType="Unspecified" preCondition="integratedMode" />
And uncomment the following lines
<remove name="UrlRoutingModule-4.0" />
<add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
Hope this helps!
I had this same issue after a recent publish of a Web API that I had recently changed the assembly name. I had no robots.txt file, so the above answers were not relevant to me. Anyway, as a solution, I simply cleaned out the folder on the server and republished.
I also had this issue on a fresh deployment to Server 2016. In the end, I actually commented out the handler mapping for URLRoutingModule and it worked. My guess is it was conflicting with something already set on the machine level.
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<!--<remove name="UrlRoutingModule-4.0"/>
<add name="UrlRoutingModule-4.0" path="*" verb="*" type="System.Web.Routing.UrlRoutingModule" preCondition=""/>-->
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
How would I delete / clear / wipe / overwrite a log file being written through EL6 logging. I am using a logwriter instance to write to a log file that needs to be overwritten every cycle as my program runs in a continuous loop. I will be writing values then overwriting as new values come through.
There may be other/better ways to attack this, but I was able to clear the log file by temporarily repointing the static LogWriter to a temp file, clearing the log with simple File I/O, and then reconnecting the original LogWriter.
I wrote up a simple C# Console App to demonstrate. There are some hard-coded references to the log file configuration in App.config that could probably be cleaned up by using the ConfigurationSourceBuilder, but hopefully this can get you started.
Programs.cs:
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using System;
using System.Diagnostics;
using System.IO;
namespace LogFileClearance
{
public static class Marker
{
public static LogWriter customLogWriter { get; set; }
}
class Program
{
private static object _syncEventId = new object();
private static object locker = new object();
private static int _eventId = 0;
private const string INFO_CATEGORY = "All Events";
static void Main( string [] args )
{
InitializeLogger();
Console.WriteLine( "Enter some input, <Enter> or q to quit, c to clear the log file" );
string input = Console.ReadLine().ToUpper();
while ( ! string.IsNullOrEmpty(input) && input != "Q" )
{
Console.WriteLine( "You entered {0}", input );
if ( input == "C" )
{
ClearLog();
}
else
{
WriteLog( input );
}
Console.WriteLine( "Enter some input, <Enter> or q to quit, c to clear the log file" );
input = Console.ReadLine().ToUpper();
}
}
private static int GetNextEventId()
{
lock ( _syncEventId )
{
return _eventId++;
}
}
public static void InitializeLogger()
{
try
{
lock ( locker )
{
if ( Marker.customLogWriter == null )
{
var writer = new LogWriterFactory().Create();
Logger.SetLogWriter( writer, false );
}
else
{
Logger.SetLogWriter( Marker.customLogWriter, false );
}
}
}
catch ( Exception ex )
{
Debug.WriteLine( "An error occurred in InitializeLogger: " + ex.Message );
}
}
static internal void WriteLog( string message )
{
LogEntry logEntry = new LogEntry();
logEntry.EventId = GetNextEventId();
logEntry.Severity = TraceEventType.Information;
logEntry.Priority = 2;
logEntry.Message = message;
logEntry.Categories.Add( INFO_CATEGORY );
// Always attach the version and username to the log message.
// The writeLog stored procedure will parse these fields.
Logger.Write( logEntry );
}
static internal void ClearLog()
{
string originalFileName = string.Format(#"C:\Logs\LogFileClearance.log");
string tempFileName = originalFileName.Replace( ".log", "(TEMP).log" );
var textFormatter = new FormatterBuilder()
.TextFormatterNamed( "Custom Timestamped Text Formatter" )
.UsingTemplate("{timestamp(local:MM/dd/yy hh:mm:ss.fff tt)} tid={win32ThreadId}: {message}");
#region Set the Logging LogWriter to use the temp file
var builder = new ConfigurationSourceBuilder();
builder.ConfigureLogging()
.LogToCategoryNamed( INFO_CATEGORY ).WithOptions.SetAsDefaultCategory()
.SendTo.FlatFile( "Flat File Trace Listener" )
.ToFile(tempFileName);
using ( DictionaryConfigurationSource configSource = new DictionaryConfigurationSource() )
{
builder.UpdateConfigurationWithReplace(configSource);
Marker.customLogWriter = new LogWriterFactory(configSource).Create();
}
InitializeLogger();
#endregion
#region Clear the original log file
if ( File.Exists(originalFileName) )
{
File.WriteAllText(originalFileName, string.Empty);
}
#endregion
#region Re-connect the original file to the log writer
builder = new ConfigurationSourceBuilder();
builder.ConfigureLogging()
.WithOptions.DoNotRevertImpersonation()
.LogToCategoryNamed( INFO_CATEGORY ).WithOptions.SetAsDefaultCategory()
.SendTo.RollingFile("Rolling Flat File Trace Listener")
.RollAfterSize(1000)
.FormatWith(textFormatter).WithHeader("").WithFooter("")
.ToFile(originalFileName);
using ( DictionaryConfigurationSource configSource = new DictionaryConfigurationSource() )
{
builder.UpdateConfigurationWithReplace( configSource );
Marker.customLogWriter = new LogWriterFactory( configSource ).Create();
}
InitializeLogger();
#endregion
}
}
}
App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<loggingConfiguration name="Logging Application Block" tracingEnabled="true" defaultCategory="" logWarningsWhenNoCategoriesMatch="true">
<listeners>
<add fileName="C:\Logs\LogFileClearance.log" footer="" formatter="Timestamped Text Formatter"
header="" rollFileExistsBehavior="Increment"
rollInterval="None" rollSizeKB="1000" timeStampPattern="yyyy-MM-dd"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" traceOutputOptions="None" filter="All" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
name="Log File Listener" />
</listeners>
<formatters>
<add template="{timestamp(local:MM/dd/yy hh:mm:ss tt)} tid={win32ThreadId}: {message}" type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="Timestamped Text Formatter" />
</formatters>
<categorySources>
<add switchValue="Information" name="All Events">
<listeners>
<add name="Log File Listener" />
</listeners>
</add>
<add switchValue="Error" name="Logging Errors & Warnings">
<listeners>
<add name="Log File Listener" />
</listeners>
</add>
</categorySources>
<specialSources>
<allEvents switchValue="Information" name="All Events" />
<notProcessed switchValue="All" name="Unprocessed Category" />
<errors switchValue="All" name="Logging Errors & Warnings" />
</specialSources>
</loggingConfiguration>
</configuration>
I have used following code to save trace log into table storage.
I'm using windows azure skd version 2.2
System.Diagnostics.Trace.TraceError("START Log");
also added listener in web.config
<system.diagnostics>
<trace>
<listeners>
<add type="Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener, Microsoft.WindowsAzure.Diagnostics, Version=2.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="AzureDiagnostics">
<filter type="" />
</add>
</listeners>
</trace>
</system.diagnostics>
also added code in webrole.cs
public override bool OnStart()
{
StartDiagnostics();
return base.OnStart();
}
private void StartDiagnostics()
{
DiagnosticMonitorConfiguration dmc = DiagnosticMonitor.GetDefaultInitialConfiguration();
TimeSpan tsOneMinute = TimeSpan.FromMinutes(1);
// Transfer logs to storage every minute
dmc.Logs.ScheduledTransferPeriod = tsOneMinute;
// Transfer verbose, critical, etc. logs
dmc.Logs.ScheduledTransferLogLevelFilter = LogLevel.Information;
// Start up the diagnostic manager with the given configuration.
try
{
DiagnosticMonitor.Start("Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString", dmc);
}
catch (Exception exp)
{
}
}
Still getting error : 500 internal server error
I have the following module
public class LowerCaseRequest : IHttpModule {
public void Init(HttpApplication context) {
context.BeginRequest += new EventHandler(this.OnBeginRequest);
}
public void Dispose() { }
public void OnBeginRequest(Object s, EventArgs e) {
HttpApplication app = (HttpApplication)s;
if (app.Context.Request.Url.ToString().ToLower().EndsWith(".aspx")) {
if (app.Context.Request.Url.ToString() != app.Context.Request.Url.ToString().ToLower()) {
HttpResponse response = app.Context.Response;
response.StatusCode = (int)HttpStatusCode.MovedPermanently;
response.Status = "301 Moved Permanently";
response.RedirectLocation = app.Context.Request.Url.ToString().ToLower();
response.SuppressContent = true;
response.End();
}
if (!app.Context.Request.Url.ToString().StartsWith(#"http://zeeprico.com")) {
HttpResponse response = app.Context.Response;
response.StatusCode = (int)HttpStatusCode.MovedPermanently;
response.Status = "301 Moved Permanently";
response.RedirectLocation = app.Context.Request.Url.ToString().ToLower().Replace(#"http://zeeprico.com", #"http://www.zeeprico.com");
response.SuppressContent = true;
response.End();
}
}
}
}
the web.config looks like
<system.web>
<httpModules>
<remove name="WindowsAuthentication" />
<remove name="PassportAuthentication" />
<remove name="AnonymousIdentification" />
<remove name="UrlAuthorization" />
<remove name="FileAuthorization" />
<add name="LowerCaseRequest" type="LowerCaseRequest" />
<add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter" />
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</httpModules>
</system.web>
It works grate on my PC running XP and IIS 5.1
but on my webserver running IIS7 and WS 2008 dosn't works, please help I don't know how to work this out.
Thanks
On IIS7 and higher use
<configuration>
<system.webServer>
<modules>
<add name="CustomModule" type="Samples.CustomModule" />
</modules>
</system.webServer>
</configuration>
Above is correct for IIS 7.5
<modules>
<add name="CustomModule" type="Samples.CustomModule" />
</modules>
the only problem I got, is that instance of application pool for particular application should be set to managed Pipeline = Integrated, not Classic..
or:
Using Classic Mode
If your application is to use Classic mode, then make sure that your application is configured for that type of pool and your modules are configured in system.web section and not in system.webServer section of web.config file.
In IIS go to feature view select module
double click to module then right click and press (Add Managed Module)
then put name and type as defined in web.config
example:
<httpModules>
<add name="CustomModule" type="WebApplication.Security.CustomModule" />
</httpModules>