Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing ELMAH database in code

I have several websites that have separate ELMAH databases. I would like to have one separate website to view all these databases.

I've created a new ASP.NET MVC 4 website for this purpose. I've added the NuGet package "Elmah.MVC" and added the following to Web.config:

<connectionStrings>
    <add name="Elmah.Sql" connectionString="..." />
</connectionStrings>
<elmah>
    <errorLog type="Elmah.SqlErrorLog" connectionStringName="Elmah.Sql" />
</elmah>

This works just fine going to a single database. I can also switch database by changing the connectionstring, but now I want to be able to switch database from code. Is there a way to do that?

like image 526
haagel Avatar asked May 06 '13 12:05

haagel


2 Answers

ELMAH has a class for customize the error log. You only need to implementing this class like

public class YourErrorLog : SqlErrorLog
{
    public override string ConnectionString
    {
        get
        {
            //return any connection string that you want
        }
    }
}

in this implementation, you can read any connection string that you want. Finally you can tell the ELMAH know about that ErrorLog by

<elmah>
    <errorLog type="YourAssembly.YourErrorLog, YourAssembly" connectionStringName="elmah-sqlserver" />
</elmah>

You can see the details here

I also found out one example in your case here

Hope this help.

like image 129
thangchung Avatar answered Oct 21 '22 18:10

thangchung


I'm retrieving the connection string at runtime so the option from ThangChung wasn't working for me. But with a few minor changes i made it work.

The SqlErrorLog, both the constructors are required.

 public class ElmahSqlErrorLog : SqlErrorLog
 {
    public override string ConnectionString
    {
        get { return SettingsXmlService.GetConnectionString(); }
    }

    public ElmahSqlErrorLog(IDictionary config) : base(config)
    {
    }

    public ElmahSqlErrorLog(string connectionString) : base(connectionString)
    {
    }
 }

The web.config (add after system.webServer)

 <elmah>
    <errorLog type="Business.Infrastructure.Elmah.ElmahSqlErrorLog, Business" connectionString="-" applicationName="Topsite" />
 </elmah>

The value of the connectionString doesn't matter because we retrieve it at runtime, it can't be empty though.

like image 45
Jamie Avatar answered Oct 21 '22 16:10

Jamie