logging services calls in .txt file - c#

I am trying to user the following code
private CModel[] getConfig(string CID, string Program)
{
ServiceManagement.ServiceClient obj;
List<ServiceManagement.ManagementApiRepositoryCConfig> executedService;
obj = new ServiceManagement.ServiceClient();
executedService = new List<SaServiceIdentityManagement.ManagementApiRepositoryCConfig>();
executedService = obj.getClubConfigSingle(CID, Program);
return executedService.Select(x => new CModel
{
CID = CID,
ProgramName = x.Name,
ProgramURL = x.Value,
}).ToArray();
}
and
using (StreamWriter w = File.AppendText("log.txt"))
{
Log("call 1", w);
Log("call 2", w);
}
What I am wanting to do is build a .txt, or xml, js/json file to log requests to the service
I am not sure why Im getting nothing added to the log.txt file
Thanks M

It sounds like you are trying to build something that already exists by default in the .net framework. I think what you're looking for is the tracing functionality that's in system.diagnostics. Try adding this to your config file:
<system.diagnostics>
<sources>
<source name="System.ServiceModel" switchValue="Information,ActivityTracing"
propagateActivity="true">
<listeners>
<add name="xml" />
</listeners>
</source>
<source name="System.ServiceModel.MessageLogging">
<listeners>
<add name="xml" />
</listeners>
</source>
</sources>
<sharedListeners>
<add initializeData="C:\logs\TracingAndLogging-client.svclog" type="System.Diagnostics.XmlWriterTraceListener"
name="xml" />
</sharedListeners>
<trace autoflush="true" />
</system.diagnostics>
It's easy and cheap to implement and there's even a special software that displays it neatly for you.
You can find more information about tracing here: https://msdn.microsoft.com/en-us/library/ms751526%28v=vs.110%29.aspx

Related

How to show the detailed stack trace in IIS?

I have an application hosted in IIS, but a null reference exception occurs:
As you can see, there's no stack trace, only a general exception "object reference not set to an instance of an object" is shown
But I don't know where the exception flows.
I am unable to replace the whole directory to the server since there is some other folders there.
Is there any way to fix this?
If you do have access to the assemblies, then +72 is almost enough for you to know which line of code is the cause,
http://odetocode.com/blogs/scott/archive/2005/01/25/funny-numbers-in-my-stack-trace.aspx
Add this to your web.config.
<system.diagnostics>
<sources>
<source name="System.ServiceModel" switchValue="Information, ActivityTracing" propagateActivity="true">
<listeners>
<add name="xml" />
</listeners>
</source>
<source name="CardSpace">
<listeners>
<add name="xml" />
</listeners>
</source>
<source name="System.IO.Log">
<listeners>
<add name="xml" />
</listeners>
</source>
<source name="System.Runtime.Serialization">
<listeners>
<add name="xml" />
</listeners>
</source>
<source name="System.IdentityModel">
<listeners>
<add name="xml" />
</listeners>
</source>
</sources>
<sharedListeners>
<add name="xml" type="System.Diagnostics.XmlWriterTraceListener" initializeData="c:\logs\Traces.svclog" />
</sharedListeners>
</system.diagnostics>
This outputs a more in depth trace log. You'll need service trace viewer tool to view it. https://msdn.microsoft.com/en-us/library/ms732023%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
Since you accepted the answer that tells you to find the offending source code line I assume that's what you want.
Deploy the PDBs that the compiler generates to production. This has no performance impact and provides line numbers.

Set logging level of autoflush .Net Trace Listener

In a .Net 4.0 web-service I am using trace autoflush to write to a log file.
By adding the following in the web.config:
<trace autoflush="true" >
<listeners>
<add name="TextWriter"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="trace.log" >
</add>
</listeners>
</trace>
Am trying to find a way to log only Trace.TraceError("error info") and exclude Trace.TraceInformation("some verbose debugging stuff") without altering my code and just changing the web.config?
The information I have found on MSDN shows how this can be done by adding code that calls Trace.Flush() and adding sources, switches and sharedlisteners, however I would like to continue using auto-flush and not alter the code.
Many thanks in advance :)
Old answer:
This appears to be impossible. Trace auto-flush does not have the
capacity to have it's level set in the web.config.
Update:
The listener may have a filter applied as follows
<configuration>
<system.diagnostics>
<trace autoflush="true" >
<listeners>
<add name="TextWriter"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="trace4.log" >
<filter type="System.Diagnostics.EventTypeFilter" initializeData="Warning" />
</add>
</listeners>
</trace>
</system.diagnostics>
Note that the initializeData is a string and may take the values of Warning or Error. This filters the trace output accordingly.
Many thanks to Josip for following up on this question.
Maybe you can use "switchValue" for this purpose like this:
<system.diagnostics>
<trace autoflush="true">
</trace>
<sources>
<source name="SCInterface" switchType="System.Diagnostics.SourceSwitch" **switchValue**="All">
<listeners>
<remove name="default"/>
<add name="HSInterface"
type="XYZ.Diagnostics.CyclicTextTraceListener, XYZ.Base3x"
initializeData="D:\Trace\HSR.HSInterface.Trace.log, Size, 10, 5"
traceOutputOptions="DateTime,ThreadId,Callstack" />
</listeners>
</source>
</sources>
</system.diagnostics>
For switch value you would put Warning or Error...

Writing to a new log file each day with TraceSource

I am using a logger in my application to write to files. The source, switch and listeners have been defined in the app.config file as follows:
<system.diagnostics>
<sources>
<source name="LoggerApp" switchName="sourceSwitch" switchType="System.Diagnostics.SourceSwitch">
<listeners>
<add name="myListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="myListener.log" />
</listeners>
</source>
</sources>
<switches>
<add name="sourceSwitch" value="Information" />
</switches>
</system.diagnostics>
Inside, my .cs code, I use the logger as follows:
private static TraceSource logger = new TraceSource("LoggerApp");
logger.TraceEvent(TraceEventType.Information, 1, "{0} : Started the application", DateTime.Now);
What would I have to do to create a new log file each day instead of writing to the same log file every time?
What would I have to do to create a new log file each day instead of writing to the same log file every time?
You'd have to make your own TraceListener instead of using TextWriterTraceListener. This would allow your TraceListener implementation to change log files daily, or do any other custom behavior you wish.
Try use:
<system.diagnostics>
<sources>
<source name="LoggerApp" switchName="sourceSwitch" switchType="System.Diagnostics.SourceSwitch">
<listeners>
<add name="myListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="myListener-{0:dd}-{0:MM}-{0:yyyy}.log" />
</listeners>
</source>
</sources>
<switches>
<add name="sourceSwitch" value="Information" />
</switches>
</system.diagnostics>

How to Resolve "The operation has timed out" error

I have a problem that while downloading the data it shows the error "The Operation has timed out".
What can i do to resolve this error? I am using Win forms(C#) here is my code please check it and give suggestions. Where should i change the code please help me...
public void ProcessData()
{
try
{
string MessageTitle = "";
int pages = Convert.ToInt32(txtPages.Text);
for (int k = Count; k <= pages; k++)
{
string url = "http://www.yellowpages.com/" +StateName.ToLower()+ "/" + CategoryName + "?g=" + StateName + "&page=" + k + "&q=" + CategoryName + "";//txtYP.Text + k;
System.Net.HttpWebRequest httpRequest;
System.Net.HttpWebResponse httpResponse;
System.IO.StreamReader SReader;
string html;
httpRequest = (System.Net.HttpWebRequest)(System.Net.HttpWebRequest.Create(url));
httpRequest.Method = "GET";
httpResponse = (System.Net.HttpWebResponse)(httpRequest.GetResponse());
SReader = new StreamReader(httpResponse.GetResponseStream());
html = SReader.ReadToEnd();
string strDummy = html;
httpResponse.Close();
How long is it before the request times out?
Are you able to navigate to the url from a web browser?
Set HttpWebRequest.ReadWriteTimeout property on HttpWebRequest to a much higher value than what it is currently. The default value is 5 minutes.
Not sure why it should take more than 5 minutes.
Instead of blocking on the getresponse, you could as well use async callbacks (BeginGetResponse/EndGetResponse).
EDIT
<system.diagnostics>
<trace autoflush="true" />
<sources>
<source name="System.Net">
<listeners>
<add name="System.Net"/>
</listeners>
</source>
<source name="System.Net.HttpListener">
<listeners>
<add name="System.Net"/>
</listeners>
</source>
<source name="System.Net.Sockets">
<listeners>
<add name="System.Net"/>
</listeners>
</source>
<source name="System.Net.Cache">
<listeners>
<add name="System.Net"/>
</listeners>
</source>
</sources>
<sharedListeners>
<add
name="System.Net"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="trace.log"
traceOutputOptions = "ProcessId, DateTime"
/>
</sharedListeners>
<switches>
<add name="System.Net"
value="Verbose" />
<add name="System.Net.Sockets"
value="Verbose" />
<add name="System.Net.Cache"
value="Verbose" />
<add name="System.Net.HttpListener"
value="Verbose" />
</switches>
</system.diagnostics>
Add this section inside configuration section in the app.config of your application.
After adding the above, rebuild the solution and run it.
Look at the trace.log written in the bin directory of your application for more details.
add this to your code :
httpRequest.Timeout = 3600000;
this will increase the request timeout to one hour.
I have face same issue while executing my console application on server. Below solution work for me :
Uncheck the automatic configuration script under Lan settings in internet option and check the automatic detect settings.
It resolve my problem for operation time out error .

WCF Tracing From Code

I have all of my connections set up from my code, as opposed to using my config file. How does one go about setting up WCF Tracing on a connection built from code. I tried adding the tracing to the config file, as explained here, but it produces no logs whatsoever.
I need to know either how to make it work from the config file for connections set up in code, or how to configure it manually in code if anyone has any info. Thanks!
EDIT: To add a little more information:
The application is a C# Console application, and my binding is declared as:
private Binding getBinding()
{
NetTcpBinding tcp = new NetTcpBinding();
tcp.ReaderQuotas.MaxArrayLength = 65535;
tcp.TransferMode = TransferMode.Streamed;
tcp.ReaderQuotas.MaxArrayLength = int.MaxValue;
tcp.ReaderQuotas.MaxDepth = int.MaxValue;
tcp.ReaderQuotas.MaxStringContentLength = int.MaxValue;
tcp.ReaderQuotas.MaxBytesPerRead = int.MaxValue;
tcp.ReaderQuotas.MaxNameTableCharCount = int.MaxValue;
tcp.MaxReceivedMessageSize = int.MaxValue;
return tcp;
}
And I then add services to my app using a generic function:
private List<ServiceHost> m_Hosts = new List<ServiceHost>();
private static List<string> m_Services = new List<string>();
public void AddHost<T1, T2>(string uri)
where T1 : class
where T2 : class
{
m_Services.Add("net.tcp://<ipaddress>:<port>/" + uri);
m_Hosts.Add(new ServiceHost(typeof(T1)));
m_Hosts[m_Hosts.Count - 1].AddServiceEndpoint(typeof(T2), getBinding(), m_Services[m_Services.Count - 1]);
}
There's obviously a little more code to make this all work, but this should give any relevant parts.
The following is an .config example to enable tracing, if you want to give it another attempt. Make sure the .config file is located in the same folder of your WCF service host.
<configuration>
<system.diagnostics>
<sources>
<source name="System.ServiceModel" switchValue="Warning" propagateActivity="true" >
<listeners>
<add name="xml"/>
</listeners>
</source>
<source name="myUserTraceSource" switchValue="Warning, ActivityTracing">
<listeners>
<add name="xml"/>
</listeners>
</source>
</sources>
<sharedListeners>
<add name="xml"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData="TraceLog.svclog" />
</sharedListeners>
</system.diagnostics>
</configuration>
Microsoft provides a Service Trace Viewer Tool to read .svclog files.
Make sure the path where you will be saving the .svclog has the necessary write permissions.
Just for the records here is how to change the log file name by code
http://geekswithblogs.net/FlippinIT/archive/2009/11/12/wcf-tracing-in-code.aspx

Categories