excel vba - vba project reference and shared state (for logging) -
say have 2 add-ins a , b - both use vb functions shared add-in c (i.e. a , b have reference vb project c).
c log messages file (e.g. c.log
) when errors detected. want c logs a.log
when functions called , b.log
when functions called b.
the naive approach set global variable in c log-file name not work, because variable singleton, last project set variable (a, or b) win.
how can done in vba?
okay - here's solution came (quite code, seems work fine):
i have logging project logging interface ilog
(instancing publicnotcreatable
) this:
public sub error(slogmessage string) end sub public sub warning(slogmessage string) end sub ' etc.
and of course implementing class clog
writes messages log-file.
, public function callers can new instance of logger:
public function new_log(byval logfilepathandname) ilog set new_clog = new clog new_clog.initialise logfilepathandname end function
then project c must have it's code in class/or classes ilog
instance in initialisation. example csharedclass
so:
private log ilog ' note: var intentionally not called molog public sub initialise(ologger ilog) set log = ologger end sub ' other functions in class want log use this: public sub someprocedure() log.error("error text") end sub
also project must have 1 public function let callers create instance, this:
public sub new_sharedclass(ologger ilog) csharedclass ' note: may want use interface instead set new_sharedclass = new csharedclass new_sharedclass.initialise ologger end sub
then projects , b use logging this:
private molog ilog public function log() ilog ' log-file name of course different proejct b if molog nothing set molog = new_log("projecta.log") set log = molog end function
all other procedures in project a/b can write log-messages (same in shared project)
log.error("error text")
when project a/b wants use shared project, can so
private mosharedclass csharedclass public function sharedclass() csharedclass if mosharedclass nothing set mosharedclass = new_sharedclass(log) set sharedclass = mosharedclass end function
now code in project a/b wants call proc on shared class can this:
sharedclass.someprocedure()
and log messages written in someprocedure
end in correct log-file
note: decided break of own naming rules, projects can use same code logging (which has benefit can move procedures projects a/b shared project or vice versa)
Comments
Post a Comment