1

I'm trying to write a log library which would use an external tool

To make the library more natural to use, i would like to be able to detect the namespace in which cout is used.

concretly the result should be used like this

namespace A
{
    void foo()
    {
          cout << "Something went very wrong" << endl;
    }
}

namespace B
{
    void bar()
    {
          cout << "C should equal 3" << endl;
    }
}

int main()
{
    B::bar();
    A::foo();
}

and the resulting output should look like this

MODULE::B : C should equal 3
MODULE::A : Something went very wrong

I already use std::streambuf to add certain keywords to the output of cout, all i need to be able to do is specify which streambuf to use in which namespace.

How do i achieve this?

Also the library i'm making is to be integrated in a project with multiple namespaces which making heavy uses of the using namespace declaration. I would need a solution which will not require to remove these declarations.

edit1: i don't care having to specify by hand which namespace is associated with which string or adding objects to any of the used namespaces (except std of course)

tiridactil
  • 389
  • 1
  • 11

3 Answers3

2

How about creating your custom logger stream? That way the user can specify the component that failed, like so:

namespace A {
    void foo()
    {
          log("A") << "Something went very wrong" << endl;
    }
}

namespace B {
    void bar()
    {
          log("B") << "C should equal 3" << endl;
    }
}

int main()
{
    B::bar();
    A::foo();
}

Perhaps less automagical, but __FILE__ macro could also give some information.

Bartek Banachewicz
  • 38,596
  • 7
  • 91
  • 135
  • adding a specific logger would do exaclty what i'm trying to achieve but has one flaw i was trying to work around which is that i would need to find and change any existing cout in order to prevent moduleless logs – tiridactil Apr 09 '13 at 12:49
  • 1
    `#defining` `cout` into something else might be the only option then. – Bartek Banachewicz Apr 09 '13 at 12:51
  • 1
    While I would not like to `#define` `cout` as a long term solution, you can use it to detect the uses of it and you can remove the define after you have changed that for your particular logging. – David Rodríguez - dribeas Apr 09 '13 at 12:56
1

This is not possible in the language. If you are using Clang you could recompile Clang to perform such a task for you.

Puppy
  • 144,682
  • 38
  • 256
  • 465
1

you may try to inject function like std::string namespace_name() in every namespace you want to show up, and then call std::cout << namespace_name() would lead most inner namespace name output

kassak
  • 3,974
  • 1
  • 25
  • 36