Avatar of npl77
npl77 asked on

Creating a Log Writer That 2 Application Write to at the Same Time C#

I have created a client/server appilcation that I am trying to debug, so  decided to create a simple  logger class to log whats going on in my code. What I think a problem is gonna be is I want the client app and the server app to write to 1 log file. Both apps will of course be running at the same time. What do I have to do to make this work because if I instanciate the logger class in the server app and then instanciate the same class in the client app without closing the StreamWriter, I think the code is gonna break. I attached my simple logger class below.
class Logger
    {
        TextWriter tw;
        public Logger()
        {
            tw = new StreamWriter(@"D:\Profiles\w6068c\Desktop\NLogFile.txt");
        }
 
        public void WriteToLogFile(string message,string sender)
        {
            tw.WriteLine(sender+ "/n" +message);
        }
     
 
        public void CloseLogger()
        {
            tw.Close();
        }
    }

Open in new window

C#

Avatar of undefined
Last Comment
Arragorn

8/22/2022 - Mon
Arragorn

you are correct about breaking code,  the file can only be opened for writing by one process at a time.  The alternatives would be to log to a database or have you looked at the Enterprise Logging in  the Best Practices Library?  You can send your "messages" to the event log.  This is the approach I have used and it does work well.
ASKER
npl77

Can you show some code how to do that??
ASKER
npl77

If anyone could tell me why the code above doesnt write to the text file that would be sufcient for my cause. Thanks
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
ASKER CERTIFIED SOLUTION
Arragorn

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question