开发者

Protecting an email password when using NLog

When using N开发者_Go百科Log as a logging instrument we can easily send messages via email, for example this is the example configuration for using Gmail as a smtp server:

<targets>
<target name="gmail" type="Mail"
        smtpServer="smtp.gmail.com"
        smtpPort="587"
        smtpAuthentication="Basic"
        smtpUsername="user@gmail.com"
        smtpPassword="password"
        enableSsl="true"
        from="emailaddress@gmail.com"
        to="recipient@example.com"
        cc="alice@example.com;bob@example.com;charlie@example.com"
      />
</targets>
<rules>
 <logger name="*" minlevel="Debug" writeTo="gmail" />
</rules>

It works like a charm. But in the above example the password is put in plain text in a configuration file.

Is there a way to protect it somehow?


Yes, you can move the NLog.config (If you have it in this file) to your app.config and then encrypt you app.config.

You can see how to encrypt the app.config here.


You could configure the logger inside code. There, you can even hide your password from anyone with a hex-editor! Plus, nobody gets any chance to mess with your config file.

Public Class MyEmailLoggerClass
    Public Sub New()
        SetNlogConfiguration()
    End Sub

    Private Sub SetNlogConfiguration()
        Private MyNLogConfiguration As New LoggingConfiguration()
        Dim myemailtarget As New MailTarget()
        Dim MailRule As New LoggingRule("myemail", LogLevel.Info, myemailtarget) 

        With myemailtarget
            .SmtpServer = "mail.724hosting.com"
            .SmtpAuthentication = SmtpAuthenticationMode.Basic
            .SmtpUserName = "myemail" & "@" & "somewhere.com"
            .SmtpPassword = "my" & "pass" & "word"
            .SmtpPort = 587
            '.Encoding = System.Text.Encoding.UTF8
            .EnableSsl = true
            .AddNewLines = True
            .Html = True
            .Layout = "${message}"
            'message options
            .To = "sometech" & "@" & "somewhere.com"
            .cc = "bob@somewhere.com,harry@somewhereelse.com"
            .From = "myapplication@here.com"
            .Header = "<h2 style='color:red'>Message from myapplication!</h2>"
            .Subject = "Report from " & myapplicationname & " on someone's computer" & ${date:F}"
            .Body = "${message}"
        End With

        LogManager.Configuration = myNlogConfig
    End Sub
End Class

To use it, put this in the sub where you want to send email:

    Public MainLogger As New MyEmailLoggerClass
    Dim Logger = LogManager.GetLogger("myemail")
    Logger.Info("Hi, this is a message from my application")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜