ATTENTION: You are viewing a page formatted for mobile devices; to view the full web page, click HERE.

Other Software > Developer's Corner

Hi, first post in the developers section

(1/5) > >>

jumper:
I have some code to show, but I'm not sure if I should post it or not. It's not a product/project, but something I use all the time. It's a function that logs to a file. I also use it for debugging because it can tell you what method the error came from. It uses reflection. It's just for developers who might be using vb.net. But I'm sure you could take the code as a skeleton and use it in some other language.

mouser:
Hi Jumper and welcome to the site.
Absolutely, share away!

jumper:
Here's what you need in the imports section:


--- Code: Visual Basic ---Imports System.IOImports System.IO.FileImports System.Reflection
And here's the function. I imagine that some people will notice that I check to see if the file is there. Then in the try block, the first thing I do is try to delete the file. I can't really remember why I did this. It may have been just wanting to make sure it was not there before creating the new file.

Here's the function, also here's what's at the top of the class that defines logfilename

--- Code: Visual Basic ---Const logFilename As String = "logFile.txt"     Public Function logFile(LogMessage As String, Optional ex As Exception = Nothing) As Boolean         If Not Exists(logFilename) Then            Try                Delete(logFilename)                Create(logFilename).Dispose()                 Using sw = AppendText(logFilename)                    sw.WriteLine(LogMessage)                End Using                Return True            Catch                Throw New Exception("File Not Found " & ex.Message)            End Try        Else            Using sw = AppendText(logFilename)                sw.WriteLine(LogMessage)            End Using        End If        Return False    End Function
And here's the way you do it if you want to know what function an error came from. Also ex.Message is optional.

--- Code: Visual Basic ---logFile(MethodBase.GetCurrentMethod.ToString & " Some Error Message " & ex.Message)
Hope someone finds this helpful. I almost forgot... when you define just the logfileName, it writes the information in the working directory. If you want to go somewhere else, just add the path to the const. And, the error text in the catch section should be changed to something else. I just didn't take the time to do it yet.

And... I made this a while ago, so it's not very OO.

wraith808:
We have code highlighting format that can make it even more useful.  There's a drop-down above the post area that has formatting for many different languages.  Visual basic is there.

jumper:
Sorry, I didn't see that. I'll fix it.

Navigation

[0] Message Index

[#] Next page

Go to full version