Access denied error when accessing usb stick files in Windows IoT core app - raspberry-pi2

I want to access files (images, text files etc.) from an USB stick on my Raspberry Pi 2 using Windows 10 IoT Core.
So I've added the to the appxmanifest file.
When using this code in my IBackgroundTask I get an access denied error in the second line:
public sealed class StartupTask : IBackgroundTask
{
public async void Run(IBackgroundTaskInstance taskInstance)
{
//...
Windows.Storage.StorageFolder sf = Windows.Storage.KnownFolders.RemovableDevices;
//get list of drives
IReadOnlyList<Windows.Storage.StorageFolder> list = await sf.GetFoldersAsync();
...
}
}
I found that I should add the fileTypeAssociation with the file types I'd like to access in Package.appxmanifest so I did that:
<?xml version="1.0" encoding="utf-8"?>
<Package xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10" xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest" xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10" xmlns:iot="http://schemas.microsoft.com/appx/manifest/iot/windows10" IgnorableNamespaces="uap mp iot">
<Identity Name="test-uwp" Publisher="CN=user" Version="1.0.0.0" />
<mp:PhoneIdentity PhoneProductId="8f31dff8-3a2b-4df1-90bb-2c5267f32980" PhonePublisherId="00000000-0000-0000-0000-000000000000" />
<Properties>
<DisplayName>test</DisplayName>
<PublisherDisplayName>user</PublisherDisplayName>
<Logo>Assets\StoreLogo.png</Logo>
</Properties>
<Dependencies>
<TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.0.0" MaxVersionTested="10.0.0.0" />
</Dependencies>
<Resources>
<Resource Language="x-generate" />
</Resources>
<Applications>
<Application Id="App">
<uap:VisualElements DisplayName="test" Square150x150Logo="Assets\Square150x150Logo.png" Square44x44Logo="Assets\Square44x44Logo.png" Description="test" BackgroundColor="transparent" AppListEntry="none">
<uap:DefaultTile Wide310x150Logo="Assets\Wide310x150Logo.png">
</uap:DefaultTile>
<uap:SplashScreen Image="Assets\SplashScreen.png" />
</uap:VisualElements>
<Extensions>
<Extension Category="windows.backgroundTasks" EntryPoint="test.StartupTask">
<BackgroundTasks>
<iot:Task Type="startup" />
</BackgroundTasks>
</Extension>
<uap:Extension Category="windows.fileTypeAssociation">
<uap:FileTypeAssociation Name="myimages">
<uap:SupportedFileTypes>
<uap:FileType ContentType="image/jpeg">.jpg</uap:FileType>
</uap:SupportedFileTypes>
</uap:FileTypeAssociation>
</uap:Extension>
</Extensions>
</Application>
</Applications>
<Capabilities>
<Capability Name="internetClient" />
<uap:Capability Name="removableStorage" />
</Capabilities>
</Package>
If I want to deploy that, I get the following error:
Severity Code Description Project File Line Suppression State
Error Error : DEP0700 : Registration of the app failed.
AppxManifest.xml(37,10): error 0x80070490: Cannot register the
test-uwp_1.0.0.0_arm__yzekw4x8qxe1g package because the following
error was encountered while parsing the windows.fileTypeAssociation
Extension element: Element not found. . Try again and contact the
package publisher if the problem persists. (0x80073cf6)
As soon as I remove the uap:Extension element, the error goes away (but the access denied is still there).
Did I miss anything? Is it not possible to access files from an USB stick using a background service (I want to run that headless with no user interaction)?

At the moment you can't register a headless app that uses filetypeAssociation.
There is a workaround - see here: https://github.com/ms-iot/ntvsiot/issues/62
Simply add a headed app (project) to your solution (no need for any special code there).
Add a reference to this project in your headless app.
Now change the manifest of the headless (file asso..) and add Executable: YourHeadedApp.exe and EntryPoint: YourHeadedApp.App now with the next deploy the EXE will be included in deployment - so it can be found when the manifest is checked.

Related

Partial view not found exception with asp.net core in IIS only

We are having problems with partial views after migrating to .net 5. The main page will optionally render a custom partial view to allow per-customer customizations. After migrating we are unable to render these partial views. the error message is:
InvalidOperationException: The partial view ~/Resources/Customer/Views/File.cshtml was not found. The following locations were searched: ~/Resources/Customer/Views/File.cshtml
We know the path is valid because if we rename the file the page renders (without customizations). If we debug in visual studio the page renders as expected but in a deployed IIS server it fails. We suspect there is a permissions issue but we have been unable to find it. So far we haven't been able to find anything in google searches or SO
Here is a snippet where we handle the custom file:
// load file path from config
string url = configuration.OrderPageSetting["OrderInfoViewRenderFile"];
bool exists = false;
// determine the path
if (!string.IsNullOrWhiteSpace(url))
{
string _url = url;
if (_url.StartsWith("~/")) _url = _url.Substring(2);
else if (_url.StartsWith("/")) _url = _url.Substring(1);
exists = System.IO.File.Exists(System.IO.Path.Combine(Resource.SystemDirectory, _url));
}
// test for and render custom view
if (exists)
{
var data = new ViewDataDictionary<object>(new EmptyModelMetadataProvider(), new ModelStateDictionary());
data.Add("Order", order);
data.Add("Config", configuration);
await Html.RenderPartialAsync(url, data);
}
else
{
... default rendering ...
}
The application is hosted in a virtual directory with a dedicated application pool. This problem occurs without a web.config at the site level. On the same server, the prior .net framework version of the application works correctly.
here is the applications web.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="." inheritInChildApplications="false">
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="dotnet" arguments=".\myapp.dll" stdoutLogEnabled="false" hostingModel="InProcess" stdoutLogFile=".\logs\stdout">
<environmentVariables>
<environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
</environmentVariables>
</aspNetCore>
</system.webServer>
</location>
</configuration>
A co-worker found the solution the problem, the clue was in https://weblog.west-wind.com/posts/2019/Sep/30/Serving-ASPNET-Core-Web-Content-from-External-Folders
There were 2 changes required:
Add package: Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation
called extension to support runtime complication on the controllers/views:
services.AddControllersWithViews().AddRazorRuntimeCompilation(opt =>
{
opt.FileProviders.Add(
new PhysicalFileProvider(System.IO.Path.Combine(Environment.ContentRootPath, ""))
);
})
if you want to change where the dynamic compilation is supported, simply change the "" to the path where it is permitted.

Infinispan local cache error: Unable to invoke method public void org.infinispan.globalstate.impl.GlobalConfigurationManagerImpl.start()

I have upgraded a Spring boot service to Infinispan 9.4.16.Final from 5.2.20.Final. The service has two XML files. I used the conversion script to convert them. Both have local-cache entries and no other types of caches. One was left with empty transport element by the conversion tool.
When we deploy and run these services, we often see this warning at startup:
org.infinispan.manager.EmbeddedCacheManagerStartupException: org.infinispan.commons.CacheException: Unable to invoke method public void org.infinispan.globalstate.impl.GlobalConfigurationManagerImpl.start() on object of type GlobalConfigurationManagerImpl
The above is the first warning/error we see. There is no stack trace. Why would it be calling GlobalConfigurationManagerImpl when we're only using local cache?
A few lines later in the log, then I see many The cache has been stopped and invocations are not allowed! errors. The last error we see is as follows. The service fails to start up successfully.
Caused by: org.infinispan.commons.CacheException: Initial state transfer timed out for cache org.infinispan.CONFIG on <server_name>
Why are these errors/warnings happening on startup? Is there a problem in the config files? I've searched online and have not found a solution.
~~More Info~~~
Here is one of the two XML config files:
<infinispan
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "urn:infinispan:config:9.4 http://www.infinispan.org/schemas/infinispan-config-9.4.xsd"
xmlns = "urn:infinispan:config:9.4">
<threads/>
<cache-container name = "TestCenterServiceCache">
<!-- The conversion tool added this empty "transport" element. It was not present in our old config file -->
<transport/>
<jmx domain = "org.infinispan.TestCenterServiceCache"/>
<local-cache name = "authorizedLocations">
<expiration lifespan = "3600000"/>
</local-cache>
<!--caching for 24 hours: 3,600,000 milliseconds/hr x 24 hours -->
<local-cache name = "proximitySearchConfiguration">
<expiration lifespan = "86400000"/>
</local-cache>
</cache-container>
</infinispan>
The above is instantiated via applicationContext.xml. The first warning (GlobalConfigurationManagerImpl.start()) is referencing these beans.
<bean id="infinispanCacheManager"
class="org.infinispan.spring.embedded.support.InfinispanEmbeddedCacheManagerFactoryBean"
p:configurationFileLocation="classpath:testCenterServices-cache-config.xml" />
<bean id="cacheManager"
class="org.infinispan.spring.embedded.provider.SpringEmbeddedCacheManager">
<constructor-arg ref="infinispanCacheManager" />
</bean>
Here is the second XML config file:
<?xml version="1.0" ?>
<infinispan
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "urn:infinispan:config:9.4 http://www.infinispan.org/schemas/infinispan-config-9.4.xsd"
xmlns = "urn:infinispan:config:9.4">
<threads />
<cache-container name="AtlasServicesCacheManager">
<local-cache name="allLocaleCache" />
<local-cache name="localeCacheByID" />
<local-cache name="countryByCode" />
<local-cache name="allActiveCountries" />
<local-cache name="allCountries" />
<local-cache name="allStatesForCountryCode" />
<local-cache name="allActiveStatesForCountryCode" />
<local-cache name="stateForCountryCodeStateCode" />
</cache-container>
</infinispan>
The above is instantiated via java code.
#Bean(name="atlasServicesCacheManager")
public CacheManager makeCacheManager() throws IOException {
return new SpringEmbeddedCacheManager(new DefaultCacheManager("atlas-cache-config.xml"));
}
I don't know if it's meaningful, but only after the upgrade, we log messages that include "JGroups", such as Unable to use any JGroups configuration mechanisms provided in properties {}. Using default JGroups configuration!.
The service instances are running on Windows Server 2012 R2 Standard (Windows 8).
To fix this, remove the empty <transport /> element for local caches.
Adding that empty element seems to be a defect in the config-converter. With the empty transport element in place, it seems that Infinispan is partially configured for cluster synchronization. For details on the underlying issue, see bug report: https://issues.redhat.com/browse/ISPN-11854.

Sitecore 8.2 ItemService api working in main website but not in microsites

I have a website that has a primary home node as well as several microsites (each of which is a different language), configured like so:
<sites>
<site name="website-swedish" itemwebapi.mode="StandardSecurity" itemwebapi.access="ReadOnly" itemwebapi.allowanonymousaccess="true" patch:source="x.Sites.config" enableTracking="true" virtualFolder="/" physicalFolder="/" rootPath="/sitecore/content" startItem="/Swedish" hostName="se.mysite.com" language="sv" database="web" domain="extranet" allowDebug="true" cacheHtml="true" htmlCacheSize="50MB" registryCacheSize="0" viewStateCacheSize="0" xslCacheSize="25MB" filteredItemsCacheSize="10MB" enablePreview="true" enableWebEdit="true" enableDebugger="true" disableClientData="false" cacheRenderingParameters="true" renderingParametersCacheSize="10MB"/>
<site name="website" enableTracking="true" virtualFolder="/" physicalFolder="/" rootPath="/sitecore/content" startItem="/home" domain="extranet" allowDebug="true" cacheHtml="true" htmlCacheSize="50MB" registryCacheSize="0" viewStateCacheSize="0" xslCacheSize="25MB" filteredItemsCacheSize="10MB" enablePreview="true" enableWebEdit="true" enableDebugger="true" disableClientData="false" cacheRenderingParameters="true" renderingParametersCacheSize="10MB" language="en" patch:source="x.Sites.config" formsRoot="{F1F7AAB6-C8CE-422F-A214-F610C109FA63}" enableItemLanguageFallback="false" enableFieldLanguageFallback="false" itemwebapi.mode="StandardSecurity" itemwebapi.access="ReadOnly" itemwebapi.allowanonymousaccess="true" database="web"/>
</sites>
InSitecore.Services.Client.config I changed SecurityPolicy to ServicesOnPolicy:
<setting name="Sitecore.Services.SecurityPolicy" value="Sitecore.Services.Infrastructure.Web.Http.Security.ServicesOnPolicy, Sitecore.Services.Infrastructure" />
When I make a call to the ItemService on my main website, such as mysite.com/sitecore/api/ssc/item/0CF2CD64-2A60-47AE-A2F2-7FD1B599EE04, it works as expected. However, when I make a call on the microsite, e.g. se.mysite.com/sitecore/api/ssc/item/0CF2CD64-2A60-47AE-A2F2-7FD1B599EE04, I get a 403 error.
In addition to the SecurityPolicy setting I also had to change the AllowAnonymousUser setting to true:
<setting name="Sitecore.Services.AllowAnonymousUser" value="true" />

NLog fails to open file on Windows with Mono

I have a small set of ServiceStack REST services that is using NLog 2.1 (from NuGet) for logging.
My test server is running:
Windows 7
IIS 7.5
.NET 4.5
NLog config:
<nlog throwExceptions="true" internalLogToConsole="true" internalLogLevel="Debug" xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="c" xsi:type="Console" />
<target name="f1" xsi:type="File" fileName="C:\logs\test.log" />
</targets>
<rules>
<logger name="*" writeTo="c,f1" />
</rules>
</nlog>
My NLog config is exceedingly simple... just trying to get it working...
and in this configuration, everything works fine. NLog creates the log files correctly.
On my DEVELOPMENT machine, I am using:
Windows 7
Xamarin Studio / XSP4
Mono 3.2.3
Here is my Application_Start...
protected void Application_Start() {
LogManager.LogFactory = new NLogFactory();
ILog log = LogManager.GetLogger(typeof(Global));
log.Info("Application_Start called");
try {
new AppHost().Init();
} catch (Exception e) {
log.Error("Exception caught initializing AppHost");
}
}
In this configuration, my service's AppHost().Init() throws an exception as ServiceStack is registering my services in ServiceController.cs. I believe that part is irrelevant except that it is the first time something is logged outside of Application_Start (because both of the calls in Application_Start work... the log.info before the exception and the log.error after the exception).
Here is the exception that is shown:
The most relevant bit is that there was a System.NotImplementedException thrown at NLog.Internal.FileAppenders.BaseFileAppender.WindowsCreateFile (System.String fileName, Boolean allowConcurrentWrite).
I have found a workaround (in the accepted answer below). Hopefully anyone else who runs into this will quickly come upon this solution.
Some digging around on Google led me to this NLog pull request:
Avoid Win32-specific file functions in Mono where parts not implemented.
It appears that this change tries to use the preprocessor to NOT call WindowsCreateFile at all. However, for some reason, this still executes.
So I then went to check the newest version of BaseFileAppender.cs in the NLog GitHub repository to make sure someone didn't at some later point break this again.
#if !NET_CF && !SILVERLIGHT && !MONO
try
{
if (!this.CreateFileParameters.ForceManaged && PlatformDetector.IsDesktopWin32)
{
return this.WindowsCreateFile(this.FileName, allowConcurrentWrite);
}
}
catch (SecurityException)
{
InternalLogger.Debug("Could not use native Windows create file, falling back to managed filestream");
}
#endif
Hmmm... it's still there. What gives? Why doesn't MONO seem to be defined by the preprocessor, thus allowing this block to execute? I'm not sure. Before I started down that path of investigation, I noticed another change...
if (!this.CreateFileParameters.ForceManaged && ...
So after following that tracing that ForceManaged boolean back to it's origin, it appeared that I could set forceManaged="true" on my FileTarget declaration in my NLog config. Could it really be that simple?!
<nlog throwExceptions="true" internalLogToConsole="true" internalLogLevel="Debug" xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="c" xsi:type="Console" />
<target name="f1" xsi:type="File" forceManaged="true" fileName="C:\logs\test.log" />
</targets>
<rules>
<logger name="*" writeTo="c,f1" />
</rules>
</nlog>
Once that change was made, everything worked... the call to WindowsCreateFile that was throwing the exception was skipped & a managed filestream was used instead, which works great. Hallelujah!
Lastly, I could not find that forceManaged flag in the NLog documentation anywhere. Would likely have found this solution sooner if it was.

sl4j/logback under weblogic

I'm trying to configure sl4j/logback under Weblogic12.
I deploy ear file, which has war file, which has WEB-INF\classes\logback.xml
Here is the config:
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="debug">
<appender-ref ref="STDOUT" />
</root>
</configuration>
My code to log :
private static final Logger logger = LoggerFactory.getLogger(FrontEndServlet.class);
//......
logger.info("info test");
logger.debug("debug test");
logger.error("error test");
What I see in the standart output is :
ьрщ 14, 2012 5:09:29 PM .....FrontEndServlet doPost
INFO: info test
ьрщ 14, 2012 5:09:29 PM .....FrontEndServlet doPost
SEVERE: error test
So, it looks like config file is not picked up.
What am I doing wrong?
The problem is discussed here in detail: https://stagingthinking.wordpress.com/2012/06/02/annoying-slf4j-problem-in-weblogic-server-12c/
The exact package you need to put to the prefer-application-packages mechanism is org.slf4j, like this:
<?xml version='1.0' encoding='UTF-8'?>
<weblogic-application>
<prefer-application-packages>
<package-name>org.slf4j</package-name>
</prefer-application-packages>
</weblogic-application>
Note: Also this question is already answered, I want to add that you should also add prefer-application-resources.
Answer: Add a file called META-INF/weblogic-application.xml to your ear, containing both prefer-application-packages and prefer-application-resources!
<?xml version="1.0" encoding="UTF-8"?>
<weblogic-application
xmlns="http://xmlns.oracle.com/weblogic/weblogic-application"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.oracle.com/weblogic/weblogic-application http://xmlns.oracle.com/weblogic/weblogic-application/1.5/weblogic-application.xsd"
version="6">
<!-- http://www.torsten-horn.de/techdocs/jee-oracleweblogic.htm -->
<prefer-application-packages>
<package-name>org.slf4j.*</package-name>
</prefer-application-packages>
<!-- if not using prefer-application-resources you will get a warning like this: -->
<!-- Class path contains multiple SLF4J bindings -->
<!-- SLF4J: Found binding in [jar:file:/C:/wls1211/modules/org.slf4j.jdk14_1.6.1.0.jar!/org/slf4j/impl/StaticLoggerBinder.class] -->
<prefer-application-resources>
<resource-name>org/slf4j/impl/StaticLoggerBinder.class</resource-name>
</prefer-application-resources>
</weblogic-application>
The problem was - sl4j did not pick up logback and used Weblogic's slf4j-jdk logging instead. Can be fixed with Weblogic's config weblogic-application.xml, option prefer-application-packages
Alternatively or if you have problems with more than just slf4j, you could use
<wls:container-descriptor>
<wls:prefer-web-inf-classes>true</wls:prefer-web-inf-classes>
</wls:container-descriptor>
Instead of
<prefer-application-packages>
<package-name>org.slf4j.*</package-name>
</prefer-application-packages>
Source: Oracle
Environment: Weblogic 12.2.1
Logging Framework : Slf4j and Logback
Requirement : Log to a file of my choosing (per application) as well as Weblogic server logs
Using the <prefer-application-packages/> or <prefer-web-inf-classes> in weblogic.xml did not satisfy the requirement. In my testing, using one or the other tags (you can't use both) will result in the application logback.xml to be picked up and logging will go to the file defined in logback.xml. However, the typical STDOUT defintion using logback's ConsoleAppender will not log to the server logs.
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
Removing the following from weblogic.xml
<wls:prefer-application-packages>
<wls:package-name>org.slf4j.*</wls:package-name>
</wls:prefer-application-packages>
will result in using the bundled SLF4j binding, which in Weblogic 12.2.1, is Java Util logging. In this case, log statements will go to the server logs and not to the file definition in the application level logback.xml. In my research, it appears at one time, some version of Weblogic 12 allowed the internal SLF4j to be bound to Log4j but was removed in one of the minor releases. This was my case; I did not have the option of enabling Log4j as the primary logging Framework in Weblogic through the Admin console. I am fairly sure this wouldn't have helped me, but I did want to note it because several documents I read indicated this would be available.
After much research and fighting configuration with weblogic.xml, configuration of POM (exclusions etc) and trying to use different bindings and bridges, I was unable to achieve the logging configuration that I wanted. It appears that Weblogic's slf4j is bound to Java utility logging, for better or worse. If you choose your own implementation of slf4j and binding (in my case Logback), there is no way that I could find to route those messages to Weblogic server logs through configuration. There can only be one binding in slf4j, and although many frameworks can be routed to that one binding, (I found this diagram useful) Weblogic 12.2.1 only employs Java util logging binding, there is no way to (at the application configuration level) to wire Weblogic to use the Logback binding that you provide to log to its server logs. There might be some way to use log4j and bridges to accomplish this, but for me that's entirely too much bloat and configuration to accomplish a simple logging task.
Giving up on trying to conquer this by configuration, I decided to simply write my own logback appender that translates a logging event into a JUL logging event. I replaced the standard STDOUT definition seen in many Logback examples with my own implementation of Logback's AppenderBase. At this point I can now log using per application logging configuration and also log to the Weblogic Server log.
Relevant POM Dependencies:
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-core -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.2.3</version>
</dependency>
weblogic.xml (Note here that Hibernate comes with JbossLogging which will bridge to slf4j automatically)
<?xml version="1.0" encoding="UTF-8"?>
<weblogic-web-app xmlns="http://xmlns.oracle.com/weblogic/weblogic-web-app"
xmlns:wls="http://xmlns.oracle.com/weblogic/weblogic-web-app"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.oracle.com/weblogic/weblogic-web-app http://xmlns.oracle.com/weblogic/weblogic-web-app/2.0/weblogic-web-app.xsd">
<jsp-descriptor>
<keepgenerated>true</keepgenerated>
<debug>true</debug>
</jsp-descriptor>
<context-root>YourContextRoot</context-root>
<wls:container-descriptor>
<wls:prefer-application-packages>
<wls:package-name>ch.qos.logback.*</wls:package-name>
<wls:package-name>org.jboss.logging.*</wls:package-name>
<wls:package-name>org.slf4j.*</wls:package-name>
</wls:prefer-application-packages>
<wls:prefer-application-resources>
<wls:resource-name>org/slf4j/impl/StaticLoggerBinder.class</wls:resource-name>
</wls:prefer-application-resources>
</wls:container-descriptor>
Logback AppenderBase implementation
import java.util.logging.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
public class WeblogicAppender extends AppenderBase<ILoggingEvent> {
private final Logger logger = Logger.getLogger(WeblogicAppender.class.getName());
ILoggingEvent event = null;
#Override
protected void append(ILoggingEvent event) {
this.event = event;
logger.log(getJULLevel(), event.getFormattedMessage());
}
private java.util.logging.Level getJULLevel() {
if (this.event == null) {
return java.util.logging.Level.SEVERE;
} else if (this.event.getLevel() == ch.qos.logback.classic.Level.ALL) {
return java.util.logging.Level.ALL;
} else if (this.event.getLevel() == ch.qos.logback.classic.Level.DEBUG) {
return java.util.logging.Level.FINE;
} else if (this.event.getLevel() == ch.qos.logback.classic.Level.ERROR) {
return java.util.logging.Level.SEVERE;
} else if (this.event.getLevel() == ch.qos.logback.classic.Level.INFO) {
return java.util.logging.Level.INFO;
} else if (this.event.getLevel() == ch.qos.logback.classic.Level.TRACE) {
return java.util.logging.Level.FINEST;
} else if (this.event.getLevel() == ch.qos.logback.classic.Level.WARN) {
return java.util.logging.Level.WARNING;
} else if (this.event.getLevel() == ch.qos.logback.classic.Level.OFF) {
return java.util.logging.Level.OFF;
} else {
return java.util.logging.Level.INFO;
}
}
}
Logback.xml configuration
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="com.your.package.WeblogicAppender">
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger: LineNumber:%L - %message%n</pattern>
</encoder>
</appender>
<appender name="FILE"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>yourlog.log
</file>
<rollingPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>yourlog.%d{yyyy-MM-dd}.%i.log
</fileNamePattern>
<maxFileSize>25MB</maxFileSize>
<maxHistory>60</maxHistory>
<totalSizeCap>10GB</totalSizeCap>
</rollingPolicy>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger: LineNumber:%L - %message%n</pattern>
</encoder>
</appender>
<root level="TRACE">
<appender-ref ref="STDOUT" />
<appender-ref ref="FILE" />
</root>
</configuration>
Hopefully I can save others some of the pain that I went through trying to get this working the way I wanted.