witch Pl/Sql logging on/off for specific sessions

 As we know Oracle provides several nice tools to debug our PlSql code and even a profiler to get all the details about code execution. But what if you want to use your own debug code and be able to switch it on for specific sessions whenever you want? And I mean, obviously, without changing the code! I’ve seen around some examples in which people use a configuration table to do that: the debug code keeps querying the table and logs the output only if the flag is Y. This way of doing it is absolutely fine and works well but I was looking for something more elegant that does not involve a table. My idea takes advantage of the Oracle application contexts and it’s really simple.

First of all, we have to create a global context. The “create any context” privilege is not commonly granted to normal users by default so we might need to do it from SYS or ask somebody to do it for us.
Let’s call this context CTX_DEBUG and make it refer to the SCOTT.PCK_DEBUG_UTILS package that we are going to create right after

Now let’s login with SCOTT and create the package PCK_DEBUG_UTILS that will support the ctx_debug context

and, just to test our code, create a very simple log table

Almost everything is ready apart from the logging procedure that populates our log table. It has to be written in a way that allows us to turn on/off the logging activity so let’s add the LOG procedure to our package

Oracle application contexts create name-value pairs that can be set and requested. By calling  sys_context on our newly created ctx_debug context and passing the current session id, we are requesting the value for a global parameter called like our session id. If the return value (using NVL because it can be null if the parameter is missing) is 1 then the log is written to the table.
Now let’s run a simple test to see how this works. Let’s run the following small PlSql block in 2 different sessions at the same time. As you can see it calls the PCK_DEBUG_UTILS.LOG procedure

If we check the log table MYLOG, there are no rows being created. Out DEBUG is still OFF! Let’s query v$sesion to get the SID of our running scripts, let’s say 155 and 158. If we want to enable logging for session 155, all we have to do is

If we query out MYLOG table now we’ll see logs coming from that specific session 155, cool isn’t it? We can enable the other one and disable logging for 155

and finally, also disable logging for session 158

I find this a nice way to implement a logging code that can be turned on in case of need on specific sessions and without changing any code.
As always, hope this is useful to some of you!

Comments

Popular posts from this blog

Flutter for Single-Page Scrollable Websites with Navigator 2.0

A Data Science Portfolio is More Valuable than a Resume

Better File Storage in Oracle Cloud