Prepending a string to a logger on function entrance - c++

I have a logger class. Call it MyLogger. I may use it in a function like this:
void MyFunc(MyLogger& oLogger)
{
//Do stuff
oLogger.Log("In MyFunc : Some Error");
//Do something else
oLogger.Log("In MyFunc : Some other error");
}
Now, I want to prepend "In MyFunc" to the logs if the log comes from inside MyFunc. Similarly for other functions...
Because this is tiresome, I tried something like this:
void MyLogger::PushPrependString(const char*)
{
//Store prepend string in stack and set it as current prepend string.
}
void MyLogger::PopPrependString()
{
//Pop the most recent prepend string.
}
Now, I can use these two functions like this:
void MyFunc(MyLogger& oLogger)
{
oLogger.PushPrependString("In MyFunc : ");
//Do stuff
oLogger.Log("Some Error");
//Do something else
oLogger.Log("Some other error");
oLogger.PopPrependString();
}
The trouble is, if there are multiple returns in a function, this becomes ugly. Is there any way around this? Is this a common problem? Is there any preprocessor macro like __FILE__ or __LINE__ for getting the name of the function a line appears in? Any comments would be appreciated. Thanks.

"The trouble is, if there are multiple returns in a function, this becomes ugly. Is there any way around this?"
Yes, just use an object with constructor (calls PushPrependString) and destructor (calls PopPrependString).
class LogPrefix
{
private:
MyLogger* logger_;
LogPrefix( LogPrefix const& ); // No such.
LogPrefix& operator=( LogPrefix const& ); // No such.
public:
LogPrefix( MyLogger& logger, char const s[] )
: logger_( &logger )
{
logger_->PushPrependString( s );
}
~LogPrefix()
{
logger_->PopPrependString();
}
};
Disclaimer: off the cuff code, not touched by compiler's hands...
"Is this a common problem?"
Yes.
"Is there any preprocessor macro like FILE or LINE for getting the name of the function a line appears in?"
Not in C++98. Various compilers offer various extensions that do that. IIRC C++0x adopts the C99 scheme, which unfortunately just provides static strings.
Cheers & hth.

RAII - Resource Acquisition Is Initialization.
In this case, you create an object on entry to the function that identifies the current function to the logging system; when the function exits (by any return or by exception thrown or by exception not caught), the object will be destroyed, and the destructor changes what is printed in future by the logging system.
In C99, and maybe in some C++ compilers such as G++, there is a predefined variable, __func__ containing the function name. The C++ equivalent is more complex, I believe.

Related

How to check for invalid/uninitialized object in c++

Currently, I've created a simple error handling system to check whether a pointer is valid by checking for nullptr like so:
inline void ErrReport(const char8* fileOfError, int32 lineNumberOfError, const Blz::string c_errMessage)
{
ErrorContext::LogContext();
LOG(" ERROR: %s\n", c_errMessage.c_str());
LOG(" In %s: %i\n\n", fileOfError, lineNumberOfError);
exit(0);
}
#if(_DEBUG)
#define ERRASSERT(test, msg) do {if (!(test)) Blz::Err::ErrReport(__FILE__, __LINE__, msg);} while (0)
#endif
I can then call ERRASSERT in my code like so:
unsgined char* imageData = LoadImage("PathToImage");
ERRASSERT(imageData, "Image did not load properly");
Right now, in order to do something similar with non-pointer objects I have a Check() function to see if an object has been initialized or not:
template<typename T> inline bool Check(boost::outcome::expected<T>& obj)
{
if (obj)
return true;
else
return false;
}
With this code, if I understand how to use outcome::expected correctly, I would then just call the above function within my ERRASSERT and everything should work similiarly
boost::outcome::expected<ObjectType> obj = functionReturnsObj();
ERRASSERT(Check(obj), "Object not initialized!);
My question:
Is there a better way to check if an object is initialized without having to wrap everything in boost::outcome::expected? Are there even many scenarios where an object wouldn't be initialized given C++ automatically initializes objects upon creation? Should I even be worried about this?
Is there a better way to check if an object is initialized
Don't.
Are there even many scenarios where an object wouldn't be initialized given C++ automatically initializes objects upon creation?
Yes, and it doesn't (always).
But that's the programmer's responsibility (and you can usually rely on compiler warnings to catch silly mistakes).
Should I even be worried about this?
No.
I just want to elaborate a bit on Should I even be worried about this? in addition to #BoundaryImposition's answer.
An uninitialized C++ object may cause you issues in certain cases. If you have Foo and create an instance f as below, then f.a and f.b are not initialized and you should not assume they are 0.
struct Foo { int a; int b; };
Foo f;

How to make a function that returns the name of the argument passed

I am looking for a way to create a naming service. Basically I need a function that accepts anything as an argument and returns me the name of the given argument. This can be anything, class, function, variable etc.
std::string name(T t)
{
if t is a function
return __func__ of t
if t is a variable
return name of variable.
}
Any suggestions?
C++ is not the right language to do this, it has no reflection capabilities at all, and you can't treat "anything, class, function, variable etc." uniformly. You can't pass a class to a function, or pass a function to a function, they are not objects.
With MACRO, you may do
#define name(n) #n
which stringify given argument.
In C++ the name of a function or of a variable is just non sense. The name is only known at build time (compile & link) and later translated to an address. At run time all names have just vanished and cannot be knows - except when using special build mode to allow debuggers to keep track of original names.
What would be closer than that would be a function accepting a pointer to void:
std::string address(const void *t) {
std::ostringstream os;
os << "Address is " << t;
return os.str();
}
You can then use it this way:
int i;
std::string s;
s = address(static_cast<const void *>(&i));
...
double d;
s = address(static_cast<const void *>(&d));
...
// if f is declared as int f(double d, std::string s):
s = address(static_cast<const void *>(&f));
As answered already, C++ doesn't have reflection. But if you have debug symbols available at runtime different OS/compiler combinations make that information available - if you put enough effort into it.
Search for mechanisms to get the C++ stack trace or back trace.
E.g., this question has multiple answers that point to libraries that are useful for Linux, and separately for Windows: C++ display stack trace on exception (There are also other answers on SO and on the web in general.)

Bad practice to call static function from external file via function pointer?

Consider the following code:
file_1.hpp:
typedef void (*func_ptr)(void);
func_ptr file1_get_function(void);
file1.cpp:
// file_1.cpp
#include "file_1.hpp"
static void some_func(void)
{
do_stuff();
}
func_ptr file1_get_function(void)
{
return some_func;
}
file2.cpp
#include "file1.hpp"
void file2_func(void)
{
func_ptr function_pointer_to_file1 = file1_get_function();
function_pointer_to_file1();
}
While I believe the above example is technically possible - to call a function with internal linkage only via a function pointer, is it bad practice to do so? Could there be some funky compiler optimizations that take place (auto inline, for instance) that would make this situation problematic?
There's no problem, this is fine. In fact , IMHO, it is a good practice which lets your function be called without polluting the space of externally visible symbols.
It would also be appropriate to use this technique in the context of a function lookup table, e.g. a calculator which passes in a string representing an operator name, and expects back a function pointer to the function for doing that operation.
The compiler/linker isn't allowed to make optimizations which break correct code and this is correct code.
Historical note: back in C89, externally visible symbols had to be unique on the first 6 characters; this was relaxed in C99 and also commonly by compiler extension.
In order for this to work, you have to expose some portion of it as external and that's the clue most compilers will need.
Is there a chance that there's a broken compiler out there that will make mincemeat of this strange practice because they didn't foresee someone doing it? I can't answer that.
I can only think of false reasons to want to do this though: Finger print hiding, which fails because you have to expose it in the function pointer decl, unless you are planning to cast your way around things, in which case the question is "how badly is this going to hurt".
The other reason would be facading callbacks - you have some super-sensitive static local function in module m and you now want to expose the functionality in another module for callback purposes, but you want to audit that so you want a facade:
static void voodoo_function() {
}
fnptr get_voodoo_function(const char* file, int line) {
// you tagged the question as C++, so C++ io it is.
std::cout << "requested voodoo function from " << file << ":" << line << "\n";
return voodoo_function;
}
...
// question tagged as c++, so I'm using c++ syntax
auto* fn = get_voodoo_function(__FILE__, __LINE__);
but that's not really helping much, you really want a wrapper around execution of the function.
At the end of the day, there is a much simpler way to expose a function pointer. Provide an accessor function.
static void voodoo_function() {}
void do_voodoo_function() {
// provide external access to voodoo
voodoo_function();
}
Because here you provide the compiler with an optimization opportunity - when you link, if you specify whole program optimization, it can detect that this is a facade that it can eliminate, because you let it worry about function pointers.
But is there a really compelling reason not just to remove the static from infront of voodoo_function other than not exposing the internal name for it? And if so, why is the internal name so precious that you would go to these lengths to hide that?
static void ban_account_if_user_is_ugly() {
...;
}
fnptr do_that_thing() {
ban_account_if_user_is_ugly();
}
vs
void do_that_thing() { // ban account if user is ugly
...
}
--- EDIT ---
Conversion. Your function pointer is int(*)(int) but your static function is unsigned int(*)(unsigned int) and you don't want to have to cast it.
Again: Just providing a facade function would solve the problem, and it will transform into a function pointer later. Converting it to a function pointer by hand can only be a stumbling block for the compiler's whole program optimization.
But if you're casting, lets consider this:
// v1
fnptr get_fn_ptr() {
// brute force cast because otherwise it's 'hassle'
return (fnptr)(static_fn);
}
int facade_fn(int i) {
auto ui = static_cast<unsigned int>(i);
auto result = static_fn(ui);
return static_cast<int>(result);
}
Ok unsigned to signed, not a big deal. And then someone comes along and changes what fnptr needs to be to void(int, float);. One of the above becomes a weird runtime crash and one becomes a compile error.

Creating a new scope with a C++ Macro?

Is this even possible? I would like to write a macro that makes it easier to use some of my classes functionality.
Lets say I have 2 member functions in my class, setup() and cleanup(), where setup() sets up parameters for some operation that needs to be executed in its own scope, and cleanup() preforms cleanup (similar to a constructor and destructor concept).
Currently, I do this:
myClassInstance.setup(); //call the setup function
{ //start scope
//CREATE LOCAL VARS
//DO STUFF IN THIS SCOPE
myClassInstance.cleanup(); //cleanup
} //end scope, destroy locals
But would like to do something like this instead:
NEWSCOPE(myClassInstance) //calls setup()
{
//CREATE LOCAL VARS
//DO STUFF IN THIS SCOPE
} // calls cleanup() and destroys locals
My thought was to write a macro class that can be instantiated when the macro is used and setup() and cleanup() could be implemented in the constructor/destructor... or something like that...
Is this the right way to think about this or is there another way to write a macro that can essentially wrap around code written by the user?
* EDIT *
I fixed the naming convention as the function names were causing come confusion.
To create a new scope just use an anonymous block.
{
Obj obj;
/*
teh codez
*/
}//obj is deallocated
So you don't need a macro
It also sounds like you startScope and endScope should actually be constructor and destructor but once again it's hard to know without knowing what they actually do
UPDATE: I tried to give you an answer but instead I'll just rant.
similar to a constructor and destructor concept
To me that sounds like they are constructors and destructors, when you have the constructor and destructor doing the setup and cleanup the operations will be performed naturally and readably with RAII.
Another thing, you say your first solution (which I sort of accidentally gave back to you) is working, why workaround with a macro, in C macros were needed to simulate features (like templates, and objects) that C++ provides. For almost every situation, especially with C++11, macros will only make things worse and harder to debug, also in your case it seems like you actually have to type more when you do the macro?
My suggestion is rethink why you need to have a macro and why setup and cleanup can't be a constructor and destructor.
You might treat this in the same way as you would acquire a mutex lock with RAII. Something like this:
class MyClassScopeBlock
{
public:
MyClassScopeBlock( MyClass & c )
: obj(c)
{
obj.startScope();
}
~MyClassScopeBlock()
{
obj.endScope();
}
private:
MyClass & obj;
};
Then instantiate that as a local variable inside a scope block:
{
MyClassScopeBlock block( myClassInstance );
//CREATE LOCAL VARS
//DO STUFF IN THIS SCOPE
}
And if you really want, you can define a macro for it, to be used inside the scope block:
#define NEWSCOPE(inst) MyClassScopeBlock block(inst)
Personally, I prefer to stay away from macros whenever possible.
I spent hours trying to figure out how to make a Macro control a scope after seeing the BOOST_FOREACH Macro. In the process of figuring it out I ran across this question hoping it held the answer! But, not quite. So, I read through all of the code for the BOOST_FOREACH and the original design for BOOST_FOREACH. Then I felt kind of dumb... A Macro essentially inserts the code directly where it is placed. This means that we can have a Macro:
#define LOOP_3() \
for(int i = 0; i < 3; ++i)
Now, let us test it out!
LOOP_3() std::cout << "Hello World!" << std::endl;
/* === Output ===
Hello World!
Hello World!
Hello World!
*/
Yay! But, how is this useful? Well, at the end of the loop what happens to i?
The destructor is called which for i is not too fancy, but the idea is there.
All we need now is a class to handle this:
class SCOPE_CONTROL {
public:
SCOPE_CONTROL(): run(1) { std::cout << "Starting Scope!" << std::endl; }
~SCOPE_CONTROL() { std::cout << "Ending Scope!" << std::endl; }
bool run;
}
Let us put that sucker to use!
#define NEWSCOPE() \
for(SCOPE_CONTROL sc = SCOPE_CONTROL(); sc.run; sc.run = 0)
...
NEWSCOPE()
std::cout << " In the Body!" << std::endl;
std::cout << "Not in body..." << std::endl;
...
/* === Output ===
Starting Scope!
In the Body!
Ending Scope!
Not in body...
*/
To use the setup and cleanup functions, just change a small bit!
class SCOPE_CONTROL {
public:
SCOPE_CONTROL(MyClass myClassInstance): control(myClassInstance), run(1) {
control.setup();
}
~SCOPE_CONTROL() { control.cleanup(); }
bool run;
MyClass & control;
}
#define NEWSCOPE(control) \
for(SCOPE_CONTROL sc = SCOPE_CONTROL(control); sc.run; sc.run = 0)
...
NEWSCOPE(myClassInstance)
{
// CREATE LOCAL VARS
// DO STUFF IN THIS SCOPE
} // end scope, destroy locals
...
To make it even better use the ENCODED_TYPE (how to make in the design for BOOST_FOREACH very simple!) to allow SCOPE_CONTROL to be a template type.
A better alternative to putting the entire scope inside the macro replacement is to use something like a finally block. I've had success encapsulating the linked solution with these macros:
#define FINALLY_NAMED( NAME, ... ) auto && NAME = \
util::finally( [&]() noexcept { __VA_ARGS__ } );
#define FINALLY( ... ) CPLUS_FINALLY_NAMED( guard, __VA_ARGS__ )
#define DO_FINALLY static_cast< void >( guard );
usage:
{
myClassInstance.setup(); //call the setup function
FINALLY ( myClassInstance.cleanup(); ) //call the cleanup function before exit
// do something
DO_FINALLY // Explicitly note that cleanup happens here. (Only a note.)
}
This is exception-safe, and cleanup executes if and only if setup completes successfully, just like a constructor/destructor pair. But the the cleanup must not throw exceptions.
But if you want to do it the old-fashioned way…
You can contain the entire scope inside the macro by using variadic macros:
#define NEWSCOPE( INSTANCE, ... ) { \
(INSTANCE).setup(); /* call the setup function */ \
{ __VA_ARGS__ } /* paste teh codez here */ \
(INSTANCE).cleanup(); /* call the cleanup function */
I would recommend against putting cleanup inside the internal scope because the point of a scope is to contain declarations and names, but you want to use the name of INSTANCE from the outer scope.
usage:
NEWSCOPE ( myClassInstance,
// Do stuff.
// Multiple declarations, anything can go here as if inside braces.
// (But no #define directives. Down, boy.)
)

Get the calling object or method in d

Somewhat related to my previous question here
Is there a way to get the calling Object from within a function or method in d?
example:
class Foo
{
public void bar()
{
auto ci = whoCalledMe();
// ci should be something that points me to baz.qux, _if_ baz.qux made the call
}
}
class Baz
{
void qux()
{
auto foo = new Foo();
foo.bar();
}
}
Questions:
Does something like whoCalledMe exist? and if so, what is it called?
if something does exist, can it be used at compile time (in a template) and if so, how?
Alternatively;
is it possible to get access to the call stack at runtime? like with php's debug_backtrace?
To expand on what CyberShadow said, since you can get the fully qualified name of the function by using __FUNCTION__, you can also get the function as a symbol using a mixin:
import std.stdio;
import std.typetuple;
void callee(string file=__FILE__, int line=__LINE__, string func=__FUNCTION__)()
{
alias callerFunc = TypeTuple!(mixin(func))[0];
static assert(&caller == &callerFunc);
callerFunc(); // will eventually overflow the stack
}
void caller()
{
callee();
}
void main()
{
caller();
}
The stack will overflow here since these two functions end up calling each other recursively indefinitely.
It's not directly possible to get information about your "caller". You might have some luck getting the address from the call stack, but this is a low-level operation and depends on things such as whether your program was compiled with stack frames. After you have the address, you could in theory convert it to a function name and line number, provided debugging symbols are available for your program's binary, but (again) this is highly platform-specific and depends on the toolchain used to compile your program.
As an alternative, you might find this helpful:
void callee(string file=__FILE__, int line=__LINE__, string func=__FUNCTION__)()
{
writefln("I was called by %s, which is in %s at line %d!", func, file, line);
}
void caller()
{
// Thanks to IFTI, we can call the function as usual.
callee();
}
But note that you can't use this trick for non-final class methods, because every call to the function will generate a new template instance (and the compiler needs to know the address of all virtual methods of a class beforehand).
Finding the caller is something debuggers do and generally requires having built the program with symbolic debug information switches turned on. Reading the debug info to figure this out is highly system dependent and is pretty advanced.
The exception unwinding mechanism also finds the caller, but those tables are not generated for functions that don't need them, and the tables do not include the name of the function.