Elad Benda
Elad Benda

Reputation: 36672

how to write to console from non-console application project

I have a sln, where a consile application is the starter of thr solution.

How is it possible to log from library project to the console?

(I mean the dll project propapbly don't allow that,

as it is not always run by the console application. Sometimes by other framework, no?)

Upvotes: 1

Views: 2666

Answers (3)

hehewaffles
hehewaffles

Reputation: 582

You could also abstract out an event so that the Class Library posts an event whenever it needs to log something; the Console Application could subscribe to the event and make a simple Console.WriteLine()

For more information, see

http://msdn.microsoft.com/en-us/library/aa645739(v=vs.71).aspx

Upvotes: 0

Tim Jarvis
Tim Jarvis

Reputation: 18825

well, a couple of points.

If you write to the console from your dll while it is part of a console app, it will in fact write to the console just fine. However I think that you instinctively know that you probably shouldn't do that from a a library because as you say, your client app will want to render it in different ways, for example a web app as html, a WPF app as XAML etc.

I would suggest that you simply provide a mechanism in your library to return your message as a string, and then leave it to the client app to render as they like.

Upvotes: 0

Kent Boogaart
Kent Boogaart

Reputation: 178820

It is technically possible for any code to use the System.Console class to write to the console. However, it is not good form for a library to do this for a number of reasons, including:

  • writing to the console is relatively expensive because a process-wide lock is required for synchronization purposes
  • writing to the console from a library will likely annoy anyone consuming that library from a console application. It would likely make the library such a hindrance that it would not be used in such a context

Instead, you would usually use a logging abstraction such as that provided by System.Diagnostics.TraceSwitch or by a logging library like log4net. Then you can configure the application to redirect logging statements to the console, another file, a database, or whatever you like really.

Upvotes: 4

Related Questions