I'm trying to setup logging across my typescript program, using log4javascript
.
However I have no idea how to retrieve the function names using reflection (rather than typed manually).
Ideally I want to emulate what I do in C#
:
public class Foo
{
private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(typeof(Foo));
public Foo()
{
}
public FooMethod()
{
try {
logger.Logger.Log(this.GetType(), log4net.Core.Level.Trace, "Entering" + MethodBase.GetCurrentMethod().Name, null);
// code
}
catch (e) {
logger.Logger.Log(this.GetType(), log4net.Core.Level.Debug, ex.Message, null);
}
finally {
logger.Logger.Log(this.GetType(), log4net.Core.Level.Trace, "Exiting" + MethodBase.GetCurrentMethod().Name, null);
}
}
}
How can I do this in Typescript
? All I can do is get the class name.
class Foo {
private static logger: log4javascript.Logger = log4javascript.getLogger(getName(Foo));
constructor() {
}
FooFunction() {
try {
SymDataSource.logger.trace("Entering: " + getName(Foo.prototype.FooFunction));
// code
} catch (e) {
SymDataSource.logger.debug("Exception: " + getName(Foo.prototype.FooFunction), e);
} finally {
SymDataSource.logger.trace("Exiting: " + getName(Foo.prototype.FooFunction));
}
}
}
function getName(obj: any): string {
if (obj.name) {
return obj.name;
}
var funcNameRegex = /function (.{1,})\(/;
var results = (funcNameRegex).exec((<any> obj).constructor.toString());
return (results && results.length > 1) ? results[1] : "";
}
The class name returns correctly, but the functions return as "Function".