You can call extended stored procedures from a function.
Some examples are:
- xp_cmdshell
- xp_regwrite
- xp_logevent
If you had the correct permissions, theoretically you could call an extended stored procedure from your function and store information like APP_NAME() and ORIGINAL_LOGIN() in a flat file or a registry key.
Another option is to build an extended stored procedure from scratch.
If all this is too much trouble, I'd follow the early recommendation of SQL Profiler or server side tracing.
An example of using an extended stored procedure is below. This uses xp_logevent to log every instance of the function call in the Windows application log.
One caveat of this method is that if the function is applied to a column in a SELECT query, it will be called for every row that is returned. That means there is a possibility you could quickly fill up the log.
Code:
USE [master]
GO
/* A security risk but will get the job done easily */
GRANT EXECUTE ON xp_logevent TO PUBLIC
GO
/* Test database */
USE [Sandbox]
GO
/* Test function which always returns 1 */
CREATE FUNCTION ufx_Function() RETURNS INT
AS
BEGIN
DECLARE
@msg VARCHAR(4000),
@login SYSNAME,
@app SYSNAME
/* Gather critical information */
SET @login = ORIGINAL_LOGIN()
SET @app = APP_NAME()
SET @msg = 'The function ufx_Function was executed by '
+ @login + ' using the application ' + @app
/* Log this event */
EXEC master.dbo.xp_logevent 60000, @msg, warning
/* Resume normal function */
RETURN 1
END
GO
/* Test */
SELECT dbo.ufx_Function()
Result:
http://yfrog.com/86pngpvp
(Screenshot of the errorlog)