Application insight log exceptions only - c#

I want to use Application Insights to log exceptions only. How can I do that?
I tried searching for ways turning other settings off such as this and it says that there is no way to turn it off.
I tried ITelemetryProcessor and encountered the same problem as this question. I tried both config and code ways of registering ITelemetryProcessor but it is not hit even if I explicitly throw an exception in my Web API controller.
I am using VS 2017 and created a new .Net Framework 4.6.2 Web API. I also have an InstrumentationKey and can see the exception logged in Azure portal.

First of all, the first link you referenced is nothing to do with your issue.
You want to only log the exceptions, but that link means that remove the old telemetry data like Trace in repository(where the telemetry data is stored after upload to app insights).
You can take use of ITelemetryProcessor to log exceptions only. Please follow my steps as below:
1.Add Application insights to your web api project by right clicking your project name -> select Configure Application Insights:
After SDK added, do not select the Enable trace collection:
2.Add a .cs file in your project, then implement your custom ITelemetryProcessor class, code is as below:
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.Extensibility;
namespace WebApplicationWebApi
{
public class ExceptionsFilter:ITelemetryProcessor
{
private ITelemetryProcessor Next { get; set; }
public ExceptionsFilter(ITelemetryProcessor next)
{
this.Next = next;
}
public void Process(ITelemetry item)
{
string s = item.GetType().Name;
//if it's not exception telemetry, just return without log it to app insights.
if (s != "ExceptionTelemetry")
{
return;
}
this.Next.Process(item);
}
}
}
3.Register your custom ITelemetryProcessor in the ApplicationInsights.config. In the node, add <Add Type="WebApplicationWebApi.ExceptionsFilter,WebApplicationWebApi"/> :
4.Then run your code. To make sure the custom ITelemetryProcessor class is called, you can set a breakpoint in that class to see if it's hit when running.
And for the testing purpose, I add some telemetry data in the HomeController.cs:
public class HomeController : Controller
{
TelemetryClient client = new TelemetryClient();
public ActionResult Index()
{
RequestTelemetry r1 = new RequestTelemetry();
r1.Name = "request message for testing";
client.TrackRequest(r1);
client.TrackTrace("trace message for testing wwwww.");
client.TrackException(new Exception("exception message for testing wwwww."));
ViewBag.Title = "Home Page";
return View();
}
}
5.In your visual studio output window, you should see these messages:
6.Then in visual studio, nav to Application Insights Search (in vs -> view -> other windows -> Application Insights Search), then check if there are some values here(if it has values like "4" in screenshot below, click on it):
7.If it has values in step 6, please click the update button, then check All:
8.Then you can see that only the Exceptions are logged:

Related

How to set Telemetry Channel for Application Insights Log4Net Appender?

I added those Nuget Packages to my WPF App:
Microsoft.ApplicationInsights.Log4NetAppender
Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel
The logger is logging in a file, that works. But no data is transferred to Azure.
I got this error:
AI: Server telemetry channel was not initialized. So persistent storage is turned off. You need to call ServerTelemetryChannel.Initialize(). Currently monitoring will continue but if telemetry cannot be sent it will be dropped.
My Question: Where (in the code) should i initialize the telemetry channel? And why do i have to do this? What's the appender for if i have to add a telemetry client (with config) anyways?
Update 0603:
my app.config:
Debug with visual studio:
Update: please follow the screenshot below, and try to find the info you send. And if you still cannot find the info, please provide you detailed code(remove the personal/important data like instrumentation key, and also provide us the nuget package and version you're using).
1.click the search button in overview page:
2.in the search screen, make the Local time and Event types are set correctly, then try to search the message:
You'd better provide the code to set log4net and app insights key.
I did a simple test with wpf project, the below code works fine:
public partial class MainWindow : Window
{
private static readonly ILog log = LogManager.GetLogger(typeof(MainWindow));
public MainWindow()
{
TelemetryConfiguration.Active.InstrumentationKey = "the key";
log4net.Config.XmlConfigurator.Configure();
log.Info("wpf aaaa11111");
InitializeComponent();
}
}
You get the error "AI: Server telemetry channel was not initialized", maybe due to some incorrect configuration, like use the following code in the above working code:
//when add the code, it will cause the error you mentioned.
TelemetryConfiguration.Active.TelemetryChannel = new ServerTelemetryChannel();
If you have to add a telemetry client (with config), and with proper configuration, both log4net and telemetry client can send data to application insights. The code like below:
public partial class MainWindow : Window
{
private readonly TelemetryClient telemetryClient;
private static readonly ILog log = LogManager.GetLogger(typeof(MainWindow));
public MainWindow()
{
//configure the key here for log4net
TelemetryConfiguration.Active.InstrumentationKey = "the key";
log4net.Config.XmlConfigurator.Configure();
var config = new TelemetryConfiguration();
//configure the key here for telemetry client
config.InstrumentationKey = "the key";
telemetryClient = new TelemetryClient(config);
log.Info("wpf aaaa333");
log.Info(TelemetryConfiguration.Active.TelemetryChannel.ToString());
telemetryClient.TrackTrace("it is going to start!");
InitializeComponent();
}
}
So, finally everything works. I offer the required steps here again:
Add NugetPackages:
log4net, Microsoft.ApplicationInsights, Microsoft.ApplicationInsights.Log4NetAppender and Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel to the Project
In MainWindow.xaml.cs:
private static readonly ILog log = LogManager.GetLogger(typeof(MainWindow));
public MainWindow()
{
TelemetryConfiguration.Active.InstrumentationKey = "the key";
log4net.Config.XmlConfigurator.Configure();
log.Info("wpf aaaa11111");
InitializeComponent();
}
}
In App.config:
Done
Big thanks to #Ivan Yang for his solution and his time helping me!

Can't use Telerik Testing Framework from web application

I recently starting fiddling around with the Telerik Test Framework ( http://www.telerik.com/teststudio/testing-framework ).
I used this to set up automated browser tests.
At first i used them in classical test project in Visual Studio and everything worked fine.
Next i wanted to be able to use the automated browser outside of Visual Studio. So i create a console application where i used the framework for my automated browser, and everything worked fine.
Next i wanted to create a MVC project where i used the framework for the automated browser, and everything stopped working.
It seems like that for some reason when the automated browser is called from a web application that the selected browser won't start up.
The actual code were the automated browser is started is the same for the web app and the console app. Just different starting points.
I also don't get any errors about the browser not starting up, i simply end up with a time out exception from the framework after i want to launch the browser.
Console code:
namespace AutomatedTests
{
class Program
{
static void Main(string[] args)
{
var telerik = new TelerikTests();
telerik.TestLanguageCoockie();
}
}
}
Web application code:
namespace AutomatedTests.Controllers
{
public class BrowserTestController : Controller
{
public ActionResult Index()
{
var telerikTests = new TelerikTests();
telerikTests.TestLanguageCoockie();
}
}
}
TelerikTests code:
namespace AutomatedTests.Tests
{
[TestClass]
public class TelerikTests : BaseTest
{
private static Settings settings;
public TelerikTests()
{
Init();
}
private Manager createMyManager
{
get
{
return new Manager(settings); // = ArtOfTest.WebAii.Core.Manager
}
}
public void Init()
{
// Get basic settings.
settings = GetSettings(); // = BaseTest.GetSettings();
// Custumize away!
settings.Web.DefaultBrowser = BrowserType.Chrome;
settings.Web.KillBrowserProcessOnClose = true;
}
[TestMethod]
public void TestLanguageCoockie()
{
var myManager = createMyManager;
myManager.Start();
myManager.LaunchNewBrowser();
// More code to perform the actual test, but with the web app approach we never get past this. The browser doesn't start and a time out exception is thrown.
}
}
}
EDIT: It turns out that i have this issue for every browser, except IE. But i do need it working for the other browsers as well.
I ended up setting up a console project + a web application. The web application contacts the console application so that it can perform all the automated browser tasks. Later it send the information back to the web app so that it can send it back to the client.

Azure MobileServiceInvalidOperation Exception has been thrown

I am working with the xamarin.forms app generated when you download the sample for working with Azure Mobile Services. I have made some modifications. Firstly, I have changed Todo, to entry.cs:
public class entry
{
string id;
[JsonProperty("ID")]
public string ID { get; set; }
[JsonProperty("Time")]
public int Time { get; set; }
[JsonProperty("Percentage")]
public int Percentage { get; set; }
//I have omitted Device, Replacement, Use_profile, Longitude, Latitude, Battery
}
I try to add a new line to the table in my SQL database, by calling the following code from my page in cs:
var data = new entry{ Longitude = await GetLongitude(), Latitude = await GetLatitude(), Percentage = bpm }; // initialise new data entry
await AddItem (data);
When this is called, the app crashes.
Here is a gist of the log when the exception is thrown. It gives a Microsoft.WindowsAzure.MobileServices.MobileServiceInvalidOpperationException has been thrown
Explanation:
The resource you are looking for has been removed, had it's name changed, or is temporarily unavailable
This is thrown on the UIApplication.Main (args, null, "AppDelegate"); line in main.cs under the ios project.
Any thoughts on why this is happening would be much appreciated.
UPDATE:
Just to add a little more info, I have a web service setup at http://project.azurewebsites.net this is the address referenced in the constants section of the mobile application I am building in xamarin. However, the SQL database is at http://project-db.database.windows.net how do I get around this? Can I create a database on the original domain, or change the reference in the app?
It looks like you are getting a 404 error when you are calling your Mobile Backend. You need to add a new Table Controller to handle the "entry" class, because your client will be trying to post to https://yourservice.azurewebsites.net/tables/entry, which doesn't exist.
In your server project, you need to add a new class Entry that inherits from EntityData. Then you add this type to your DbContext class and add a table controller. This tutorial for Mobile Services controllers might be helpful. If you're using Mobile Apps, you would use Add -> New Scaffolded Item -> Azure Mobile Apps -> Mobile Apps Table Controller.
Then, deploy your server project so that the new REST endpoint is available and then your client app should be able to connect.
Edited to add: you specify the connect to the SQL Database in the MS_TableConnectionString setting in web.config. Whatever value is the Connection Strings section of the Azure Portal will override this. For more information, see https://azure.microsoft.com/en-us/documentation/articles/web-sites-configure/.

How to track 500 errors on WebSockets (ws://)

I'm trying to play around with WebSockets on IIS 8.5. I started off with a couple of very basic C# classes from a lesson:
using Microsoft.Web.WebSockets;
using System.Web;
public class ChatHttpHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if (context.IsWebSocketRequest)
context.AcceptWebSocketRequest(new WebSocketChatHandler());
}
public bool IsReusable
{
get { return true; }
}
}
public class WebSocketChatHandler : WebSocketHandler
{
private static WebSocketCollection clients = new WebSocketCollection();
private string name;
public override void OnOpen()
{
this.name = this.WebSocketContext.QueryString["username"];
clients.Add(this);
clients.Broadcast(string.Format("{0} joined.", name));
}
public override void OnMessage(string message)
{
clients.Broadcast(string.Format("{0}: {1}", name, message));
}
public override void OnClose()
{
clients.Remove(this);
clients.Broadcast(string.Format("{0} left.", name));
}
}
and a simple HTML client. The project builds ok, but when I try to connect to the handler, it returns error 500. The problem is that I cannot see what the exact error is, because neither Chrome nor FF load the response body for ws:// scheme, so i cannot even see it in the Network tab of Developer Tools (though IIS provides the body, as I can see from from the response' Content-Length).
Is there a way to see the response body in this situation? Or what am I missing with WebSockets in IIS?
The problem was with web.config.
I added
<httpRuntime targetFramework="4.5.1" />
to system.web section and it finally began to work
You should be able to see the cause of the error in the Windows Event Viewer.
Fiddler will show you the connection and that it has upgraded to web socket so you can use that tool to at least show you if the connection worked or not. I'm not aware of a tool which can show you the traffic flowing over the socket once it has been upgraded although there might be one.
Better still, debug it in Visual Studio with breakpoints and 'break on exception' set. You can tell VS to use IIS as the server by right clicking the web site and going to Property Pages then Start Options. Tick Use custom server and put your URL into the textbox. Click Specific page and choose your default page.
Comparing it to my working solution using the same DLL, I don't spot any obvious issues with the handling of the socket, so I would suggest commenting out this.name = this.WebSocketContext.QueryString["username"]; for now and replacing it with this.name = "TEST"; as that appears to be about the only code which deviates from the samples. Keep it simple until its working!

How to display errors with ASP.NET Core

I have a fairly simple website that I am playing with using ASP.NET Core. I am running the application from the command line and the website is returning static files but I keep getting 500 errors when I attempt to make a request that should get handled by MVC. How do I see what the error is? Whether the error is displayed to the browser or logged to the console doesn't matter I just want a way to see what the error is.
Add the error page middleware as shown here:
app.UseDeveloperExceptionPage();
Update for beta8:
In beta8 Microsoft changed the name to UseDeveloperExceptionPage. So if you want to use the ErrorPage, call:
app.UseDeveloperExceptionPage();
Here is the link to the related Github issue.
The ErrorPageOptions are the same as in beta6/7.
You can use
app.UseErrorPage(ErrorPageOptions.ShowAll)
until beta5 of Asp.Net Mvc.
As of beta6, ErrorPageOptions.ShowAll has been removed. You can now use the version without parameters
app.UseErrorPage();
or create an ErrorPageOptions object and specify how many lines around the error you want to display by setting SourceCodeLineCount.
app.UseErrorPage(new ErrorPageOptions() {SourceCodeLineCount = 100});
Additional Information
They removed multiple properties of ErrorPageOptions in this commit.
Before:
public class ErrorPageOptions
{
private bool _defaultVisibility;
private bool? _showExceptionDetails;
private bool? _showSourceCode;
private bool? _showQuery;
private bool? _showCookies;
private bool? _showHeaders;
private bool? _showEnvironment;
...
}
After:
public class ErrorPageOptions
{
public int SourceCodeLineCount { get; set; }
public IFileProvider FileProvider { get; set; }
...
}
So now you can only set how many lines of source code are printed.
If you don't care that your error details would be exposed to the world, you can enable the error details, right in the browser without any code changes. (This was only tested in IIS 8.5):
In IIS Manager, in the left Connections section, left-click select your Site.
In the right side Feature View open Error Pages.
On the far right Actions section, click on Edit Feature Settings
In the Error Responses, select the 2nd, Detailed errors, option then Ok (or if you are worried about exposing stuff to the world, start with the 3rd option, if you can open a local browser... ie, localhost:...)
This should be enough for you to be able to see the exact error... Important: If you had to use the middle Detailed errors option, be sure to turn it off once you debug the problem. This can give a hacker all he needs to break into your server.
If it is not important to expose the detail of the error to the world, then you can activate detailed error page in web.config.
Just add <customErrors mode="Off"/> in the <configuration> / <system.web> of your web.config file located in root folder of your web site.
For more detailed explanation:
How to Use Web.Config customErrors for ASP.NET
This has the advantage that you don't have to redeploy your site

Categories