# Is there a way to find out who is importing a package?

After calling some functions, if I look into \$ContextPath, I can see that JLink is in there. Is there a way to find out what sequence of functions calls (like a stack-trace) imported a particular package?

Something like FuncA called FuncB which called FuncD which executed Needs["JLink"]

-

Well, here is a suggestion: you can overload Needs using Villegas-Gayley trick. To do this safely, here is a generator for local environments, where Needs will be overloaded:

createTraceEnvironment[context_String]:=
Module[{inNeeds},
Function[
code,
InternalInheritedBlock[
{Needs},
Unprotect[Needs];
Needs[context]/;!TrueQ[inNeeds]:=
Block[{inNeeds=True},
Print[Stack[_][[3;;-5]]];Needs[context]
];
Protect[Needs];
code
],
HoldAll
]
];


Now here is how it can be used: first create a local environment for "JLink":

env = createTraceEnvironment["JLink"];


Now it can be used, for example:

env[Needs["DatabaseLink"]]

{
Needs[DatabaseLink],
<<DatabaseLinkDatabaseLink;,
<<DatabaseLinkDatabaseLink, Get[ToFileName[/Applications/Mathematica_10_Sep_26_2013.app/SystemFiles/Links/DatabaseLink/Kernel,DataSources.m]];Get[ToFileName[/Applications/Mathematica_10_Sep_26_2013.app/SystemFiles/Links/DatabaseLink/Kernel,SQL.m]];,
Needs[JLink];

But loading packages (or executing other code) which load "JLink", without the local environment, will go as usual. For example, RLink also loads JLink, but here nothing is printed:
Needs["RLink"]
`